Skip to content

Commit

Permalink
Browse files Browse the repository at this point in the history
  • Loading branch information
victoriaum committed Feb 7, 2023
1 parent 43ad40e commit 023a608
Showing 1 changed file with 21 additions and 0 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,12 @@
package com.redislabs.university.RU102J.dao;

import com.redislabs.university.RU102J.core.KeyHelper;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;

import java.time.ZonedDateTime;

public class RateLimiterSlidingDaoRedisImpl implements RateLimiter {

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

Transaction t = jedis.multi();
String member = now + "-" + Math.random();
t.zadd(key, now, member);
t.zremrangeByScore(key, 0, now - windowSizeMS);
Response hits = t.zcard(key);
t.exec();

if (hits.get() > maxHits) {
throw new RateLimitExceededException();
}
}
// END CHALLENGE #7
}
}

0 comments on commit 023a608

Please sign in to comment.