Skip to content

Commit e24ead3

Browse files
author
Simon Prickett
committed
Challenge redislabs-training#7 solution and tests.
1 parent 8e66633 commit e24ead3

File tree

2 files changed

+22
-3
lines changed

2 files changed

+22
-3
lines changed

src/main/java/com/redislabs/university/RU102J/dao/RateLimiterSlidingDaoRedisImpl.java

+22
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,13 @@
11
package com.redislabs.university.RU102J.dao;
22

3+
import com.redislabs.university.RU102J.core.KeyHelper;
4+
5+
import redis.clients.jedis.Jedis;
36
import redis.clients.jedis.JedisPool;
7+
import redis.clients.jedis.Response;
8+
import redis.clients.jedis.Transaction;
9+
10+
import java.time.ZonedDateTime;
411

512
public class RateLimiterSlidingDaoRedisImpl implements RateLimiter {
613

@@ -19,6 +26,21 @@ public RateLimiterSlidingDaoRedisImpl(JedisPool pool, long windowSizeMS,
1926
@Override
2027
public void hit(String name) throws RateLimitExceededException {
2128
// START CHALLENGE #7
29+
try (Jedis jedis = jedisPool.getResource()) {
30+
String key = KeyHelper.getKey("limiter:" + windowSizeMS + ":" + name + ":" + maxHits);
31+
long now = ZonedDateTime.now().toInstant().toEpochMilli();
32+
33+
Transaction t = jedis.multi();
34+
String member = now + "-" + Math.random();
35+
t.zadd(key, now, member);
36+
t.zremrangeByScore(key, 0, now - windowSizeMS);
37+
Response<Long> hits = t.zcard(key);
38+
t.exec();
39+
40+
if (hits.get() > maxHits) {
41+
throw new RateLimitExceededException();
42+
}
43+
}
2244
// END CHALLENGE #7
2345
}
2446
}

src/test/java/com/redislabs/university/RU102J/dao/RateLimiterSlidingDaoRedisImplTest.java

-3
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,6 @@ public void flush() {
3737
keyManager.deleteKeys(jedis);
3838
}
3939

40-
@Ignore
4140
@Test
4241
public void hit() {
4342
int exceptionCount = 0;
@@ -54,7 +53,6 @@ public void hit() {
5453
assertThat(exceptionCount, is(0));
5554
}
5655

57-
@Ignore
5856
@Test
5957
public void hitOutsideLimit() {
6058
int exceptionCount = 0;
@@ -71,7 +69,6 @@ public void hitOutsideLimit() {
7169
assertThat(exceptionCount, is(2));
7270
}
7371

74-
@Ignore
7572
@Test
7673
public void hitOutsideWindow() throws InterruptedException {
7774
int exceptionCount = 0;

0 commit comments

Comments
 (0)