Redission 中 RPermitExpirableSemaphore 用法
Posted 永远的七号
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了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 执行成功与失败
以上是关于Redission 中 RPermitExpirableSemaphore 用法的主要内容,如果未能解决你的问题,请参考以下文章