|
1 | 1 | package com.redislabs.university.RU102J.dao; |
2 | 2 |
|
| 3 | +import com.redislabs.university.RU102J.core.KeyHelper; |
| 4 | + |
| 5 | +import java.time.ZonedDateTime; |
| 6 | +import java.util.UUID; |
| 7 | + |
| 8 | +import redis.clients.jedis.Jedis; |
3 | 9 | import redis.clients.jedis.JedisPool; |
| 10 | +import redis.clients.jedis.Response; |
| 11 | +import redis.clients.jedis.Transaction; |
4 | 12 |
|
5 | 13 | public class RateLimiterSlidingDaoRedisImpl implements RateLimiter { |
6 | 14 |
|
7 | | - private final JedisPool jedisPool; |
8 | | - private final long windowSizeMS; |
9 | | - private final long maxHits; |
10 | | - |
11 | | - public RateLimiterSlidingDaoRedisImpl(JedisPool pool, long windowSizeMS, |
12 | | - long maxHits) { |
13 | | - this.jedisPool = pool; |
14 | | - this.windowSizeMS = windowSizeMS; |
15 | | - this.maxHits = maxHits; |
16 | | - } |
17 | | - |
18 | | - // Challenge #7 |
19 | | - @Override |
20 | | - public void hit(String name) throws RateLimitExceededException { |
21 | | - // START CHALLENGE #7 |
22 | | - // END CHALLENGE #7 |
23 | | - } |
| 15 | + private final JedisPool jedisPool; |
| 16 | + private final long windowSizeMS; |
| 17 | + private final long maxHits; |
| 18 | + |
| 19 | + public RateLimiterSlidingDaoRedisImpl( JedisPool pool, long windowSizeMS, long maxHits ) { |
| 20 | + this.jedisPool = pool; |
| 21 | + this.windowSizeMS = windowSizeMS; |
| 22 | + this.maxHits = maxHits; |
| 23 | + } |
| 24 | + |
| 25 | + // Challenge #7 |
| 26 | + @Override |
| 27 | + public void hit( String name ) throws RateLimitExceededException { |
| 28 | + // START CHALLENGE #7 |
| 29 | + try ( Jedis jedis = jedisPool.getResource(); Transaction t = jedis.multi() ) { |
| 30 | + long currentMs = ZonedDateTime.now().toInstant().toEpochMilli(); |
| 31 | + |
| 32 | + // make the member unique in order not to replace the score of another one |
| 33 | + String member = String.format( "%s:%s", currentMs, UUID.randomUUID() ); |
| 34 | + String key = KeyHelper.getKey( String.format( "limiter:%s:%s:maxHits", windowSizeMS, name ) ); |
| 35 | + t.zadd( key, currentMs, member ); |
| 36 | + t.zremrangeByScore( key, 0, currentMs - windowSizeMS ); // remove hits before the current sliding window |
| 37 | + Response<Long> hitCount = t.zcard( key ); |
| 38 | + t.exec(); |
| 39 | + |
| 40 | + if ( hitCount.get() > maxHits ) { |
| 41 | + throw new RateLimitExceededException(); |
| 42 | + } |
| 43 | + } |
| 44 | + // END CHALLENGE #7 |
| 45 | + } |
24 | 46 | } |
0 commit comments