Skip to content

Commit

Permalink
Challenge redislabs-training#7 solution and tests.
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon Prickett committed May 30, 2020
1 parent 8e66633 commit e24ead3
Show file tree
Hide file tree
Showing 2 changed files with 22 additions and 3 deletions.
Original file line number Diff line number Diff line change
@@ -1,6 +1,13 @@
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 +26,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<Long> hits = t.zcard(key);
t.exec();

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

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

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

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

0 comments on commit e24ead3

Please sign in to comment.