27 Mart 2023 Pazartesi

SpringData Redis ZSetOperations Sınıfı

removeRangeByScore metodu
Örnek
Şöyle yaparız
public Set<String> rateLimiter(String id) {
  String key = "rate-" + id;
  long currentTime = System.currentTimeMillis();
  long slidingWindowTime = 60_000L; //1 min, This is basically the rate limit time.

  List<Object> valOuter =  redisTemplate.execute(new SessionCallback<List<Object>>() {
    @Override
    public List<Object> execute(@NotNull RedisOperations operations) throws DataAccessException {
      operations.multi();
      operations.opsForZSet().removeRangeByScore(key, 0, currentTime - slidingWindowTime);
      operations.opsForZSet().add(key, Long.toString(currentTime), currentTime);
      operations.expire(key, currentTime + slidingWindowTime, TimeUnit.MILLISECONDS);
      redisTemplate.opsForZSet().range(key, 0, -1);
      return operations.exec();
    }
  });
  log.info("EmployeeDao: rateLimiter: {}", valOuter);

  return valOuter != null ? (Set<String>) valOuter.get(valOuter.size()-1) : Collections.emptySet() ;
}


Hiç yorum yok:

Yorum Gönder