基于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;
    }
}

最后编辑时间:2023年12月29日21:37:27

posted @ 2023-12-29 21:38  tothk  阅读(138)  评论(0编辑  收藏  举报