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 执行成功与失败 

posted @ 2018-09-05 21:11  永远的七号  阅读(1012)  评论(0编辑  收藏