Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
Rate limiter
Implement `hit()` in `RateLimiterSlidingDaoRedisImpl.java`.
  • Loading branch information
J-A-I-L committed Jul 11, 2022
1 parent aaf1fb0 commit 09f7064
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,9 @@
package com.redislabs.university.RU102J.dao;

import redis.clients.jedis.JedisPool;
import com.redislabs.university.RU102J.core.KeyHelper;
import redis.clients.jedis.*;

import java.util.UUID;

public class RateLimiterSlidingDaoRedisImpl implements RateLimiter {

Expand All @@ -19,6 +22,23 @@ public RateLimiterSlidingDaoRedisImpl(JedisPool pool, long windowSizeMS,
@Override
public void hit(String name) throws RateLimitExceededException {
// START CHALLENGE #7
try (Jedis jedis = jedisPool.getResource()) {
String keyName = "limiter" + ":" + windowSizeMS + ":" + name + ":" + maxHits;
String key = KeyHelper.getKey(keyName);

final Transaction transaction = jedis.multi();
final long currentTimeStamp = System.currentTimeMillis();
final UUID uuid = UUID.randomUUID();
final String member = "" + currentTimeStamp + "-" + uuid;
transaction.zadd(key, currentTimeStamp, member);
transaction.zremrangeByScore(key,0, currentTimeStamp - windowSizeMS);
final Response<Long> hits = transaction.zcard(key);
transaction.exec();

if (hits.get() > maxHits) {
throw new RateLimitExceededException();
}
}
// END CHALLENGE #7
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,6 @@ public void flush() {
keyManager.deleteKeys(jedis);
}

@Ignore
@Test
public void hit() {
int exceptionCount = 0;
Expand All @@ -64,7 +63,6 @@ public void hit() {
assertThat(exceptionCount, is(0));
}

@Ignore
@Test
public void hitOutsideLimit() {
int exceptionCount = 0;
Expand All @@ -81,7 +79,6 @@ public void hitOutsideLimit() {
assertThat(exceptionCount, is(2));
}

@Ignore
@Test
public void hitOutsideWindow() throws InterruptedException {
int exceptionCount = 0;
Expand Down

0 comments on commit 09f7064

Please sign in to comment.