基于Redis的简单漏桶算法
下列代码是限制每秒10QPS的简单算法,需要修改频率请修改Duration.ofMillis(100)
处
public class LimitationManage {
private static final String VALUE = "A";
@Resource
private RedissonClient redissonClient;
public Boolean tryAcquire(String key) {
try {
RBucket<String> rBucket = redissonClient.getBucket(key);
if (rBucket.get() != null) {
return Boolean.FALSE;
} else {
String lockStr = "LOCK:" + key;
RReadWriteLock rReadWriteLock = redissonClient.getReadWriteLock(lockStr);
RLock writeLock = rReadWriteLock.writeLock();
if (writeLock.tryLock(0, 1, TimeUnit.SECONDS)) {
boolean absent = rBucket.setIfAbsent(VALUE, Duration.ofMillis(100));
if (!absent) {
return Boolean.FALSE;
}
} else {
return Boolean.FALSE;
}
if (writeLock.isLocked()) {
if (writeLock.isHeldByCurrentThread()) {
writeLock.unlock();
}
}
}
} catch (InterruptedException e) {
throw new RuntimeException(e);
}
return Boolean.TRUE;
}
}