From 09f7064e5e34b705417e93c9fee63c91ce4982be Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Jose=20A=2E=20I=2E=20L=C3=B3pez?= <17472377+J-A-I-L@users.noreply.github.com> Date: Mon, 11 Jul 2022 23:57:46 +0200 Subject: [PATCH] Challenge #7 Rate limiter Implement `hit()` in `RateLimiterSlidingDaoRedisImpl.java`. --- .../dao/RateLimiterSlidingDaoRedisImpl.java | 22 ++++++++++++++++++- .../RateLimiterSlidingDaoRedisImplTest.java | 3 --- 2 files changed, 21 insertions(+), 4 deletions(-) diff --git a/src/main/java/com/redislabs/university/RU102J/dao/RateLimiterSlidingDaoRedisImpl.java b/src/main/java/com/redislabs/university/RU102J/dao/RateLimiterSlidingDaoRedisImpl.java index a1b1947..dd2316b 100644 --- a/src/main/java/com/redislabs/university/RU102J/dao/RateLimiterSlidingDaoRedisImpl.java +++ b/src/main/java/com/redislabs/university/RU102J/dao/RateLimiterSlidingDaoRedisImpl.java @@ -1,6 +1,9 @@ package com.redislabs.university.RU102J.dao; -import redis.clients.jedis.JedisPool; +import com.redislabs.university.RU102J.core.KeyHelper; +import redis.clients.jedis.*; + +import java.util.UUID; public class RateLimiterSlidingDaoRedisImpl implements RateLimiter { @@ -19,6 +22,23 @@ public RateLimiterSlidingDaoRedisImpl(JedisPool pool, long windowSizeMS, @Override public void hit(String name) throws RateLimitExceededException { // START CHALLENGE #7 + try (Jedis jedis = jedisPool.getResource()) { + String keyName = "limiter" + ":" + windowSizeMS + ":" + name + ":" + maxHits; + String key = KeyHelper.getKey(keyName); + + final Transaction transaction = jedis.multi(); + final long currentTimeStamp = System.currentTimeMillis(); + final UUID uuid = UUID.randomUUID(); + final String member = "" + currentTimeStamp + "-" + uuid; + transaction.zadd(key, currentTimeStamp, member); + transaction.zremrangeByScore(key,0, currentTimeStamp - windowSizeMS); + final Response hits = transaction.zcard(key); + transaction.exec(); + + if (hits.get() > maxHits) { + throw new RateLimitExceededException(); + } + } // END CHALLENGE #7 } } diff --git a/src/test/java/com/redislabs/university/RU102J/dao/RateLimiterSlidingDaoRedisImplTest.java b/src/test/java/com/redislabs/university/RU102J/dao/RateLimiterSlidingDaoRedisImplTest.java index b54dd0c..aec5131 100644 --- a/src/test/java/com/redislabs/university/RU102J/dao/RateLimiterSlidingDaoRedisImplTest.java +++ b/src/test/java/com/redislabs/university/RU102J/dao/RateLimiterSlidingDaoRedisImplTest.java @@ -47,7 +47,6 @@ public void flush() { keyManager.deleteKeys(jedis); } - @Ignore @Test public void hit() { int exceptionCount = 0; @@ -64,7 +63,6 @@ public void hit() { assertThat(exceptionCount, is(0)); } - @Ignore @Test public void hitOutsideLimit() { int exceptionCount = 0; @@ -81,7 +79,6 @@ public void hitOutsideLimit() { assertThat(exceptionCount, is(2)); } - @Ignore @Test public void hitOutsideWindow() throws InterruptedException { int exceptionCount = 0;