Skip to content

Commit

Permalink
Finish challenge redislabs-training#7
Browse files Browse the repository at this point in the history
  • Loading branch information
quyluongthanh committed Feb 8, 2023
1 parent 0890554 commit 26d1bf2
Show file tree
Hide file tree
Showing 3 changed files with 40 additions and 4 deletions.
Original file line number Diff line number Diff line change
@@ -1,11 +1,17 @@
package com.redislabs.university.RU102J.dao;

import java.time.Instant;
import java.time.ZonedDateTime;
import java.util.UUID;
import redis.clients.jedis.Jedis;
import redis.clients.jedis.JedisPool;
import redis.clients.jedis.Response;
import redis.clients.jedis.Transaction;

public class RateLimiterSlidingDaoRedisImpl implements RateLimiter {

private final JedisPool jedisPool;
private final long windowSizeMS;
private final long windowSizeMS; // in milli
private final long maxHits;

public RateLimiterSlidingDaoRedisImpl(JedisPool pool, long windowSizeMS,
Expand All @@ -20,5 +26,29 @@ public RateLimiterSlidingDaoRedisImpl(JedisPool pool, long windowSizeMS,
public void hit(String name) throws RateLimitExceededException {
// START CHALLENGE #7
// END CHALLENGE #7

String key = RedisSchema.getRateLimiterSlidingKey(windowSizeMS, name, maxHits);
Instant instant = ZonedDateTime.now().toInstant();
long currTimestampInMilli = instant.toEpochMilli();
long milestoneTimestampInMilli = currTimestampInMilli - windowSizeMS;
String randomNumber = UUID.randomUUID().toString();

try (Jedis jedis = jedisPool.getResource()) {
Transaction multi = jedis.multi();

multi.zadd(
key,
currTimestampInMilli,
randomNumber
);
multi.zremrangeByScore(key, 0, milestoneTimestampInMilli);
Response<Long> hits = multi.zcard(key);

multi.exec();

if (hits.get() > maxHits) {
throw new RateLimitExceededException();
}
}
}
}
Original file line number Diff line number Diff line change
Expand Up @@ -42,6 +42,12 @@ static String getRateLimiterKey(String name, int minuteBlock,
String.valueOf(minuteBlock) + ":" +
String.valueOf(maxHits));
}

static String getRateLimiterSlidingKey(long windowSize, String name, long maxHits) {
return KeyHelper.getKey(
String.format("limiter:%s:%s:%s", windowSize, name, maxHits)
);
}

// sites:geo
// Redis type: geo
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -47,7 +47,7 @@ public void flush() {
keyManager.deleteKeys(jedis);
}

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

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

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

0 comments on commit 26d1bf2

Please sign in to comment.