Redission 中 RPermitExpirableSemaphore 用法


關於該類,https://github.com/redisson/redisson 上的解釋如下

基於Redis的Java 分布式Semaphore對象,每個獲取的許可證具有租用時間參數支持。每個許可證由自己的id標識,並且只能使用其id發布。

8.7. PermitExpirableSemaphore
Redis based distributed Semaphore object for Java with lease time parameter support for each acquired permit. Each permit identified by own id and could be released only using its id.

RPermitExpirableSemaphore semaphore = redisson.getPermitExpirableSemaphore("mySemaphore");
String permitId = semaphore.acquire();
// acquire permit with lease time = 2 seconds
String permitId = semaphore.acquire(2, TimeUnit.SECONDS);
// ...
semaphore.release(permitId);

 

private final RPermitExpirableSemaphore initSemaphore(Config config) {
        RPermitExpirableSemaphore semaphore = redissonClient.getPermitExpirableSemaphore(config.getId());
        semaphore.delete();
        semaphore = redissonClient.getPermitExpirableSemaphore(config.getId());
        semaphore.trySetPermits(config.getLimit());
        return semaphore;
    }

 

lua腳本很簡單,如果keys1不存在,給keys1賦值,發布,並且返回1;如果keys1存在,直接返回0

   @Override
    public RFuture<Boolean> trySetPermitsAsync(int permits) {
        return commandExecutor.evalWriteAsync(getName(), LongCodec.INSTANCE, RedisCommands.EVAL_BOOLEAN,
                "local value = redis.call('get', KEYS[1]); " +
                "if (value == false or value == 0) then "
                    + "redis.call('set', KEYS[1], ARGV[1]); "
                    + "redis.call('publish', KEYS[2], ARGV[1]); "
                    + "return 1;"
                + "end;"
                + "return 0;",
                Arrays.<Object>asList(getName(), getChannelName()), permits);
    }

關於 commandExecutor 執行成功與失敗 


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM