Skip to content

Commit 023a608

Browse files
committed
1 parent 43ad40e commit 023a608

File tree

1 file changed

+21
-0
lines changed

1 file changed

+21
-0
lines changed

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

Lines changed: 21 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,12 @@
11
package com.redislabs.university.RU102J.dao;
22

3+
import com.redislabs.university.RU102J.core.KeyHelper;
4+
import redis.clients.jedis.Jedis;
35
import redis.clients.jedis.JedisPool;
6+
import redis.clients.jedis.Response;
7+
import redis.clients.jedis.Transaction;
8+
9+
import java.time.ZonedDateTime;
410

511
public class RateLimiterSlidingDaoRedisImpl implements RateLimiter {
612

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

0 commit comments

Comments
 (0)