前言
前面已经写了Redisson大多的内容,我们再看看Redisson官网共有哪些组件:
image.png
剩下还有Semaphore和CountDownLatch两块,我们就趁热打铁,赶紧看看Redisson是如何实现的吧。
我们在JDK中都知道Semaphore和CountDownLatch两兄弟,这里就不多赘述,不了解的可以再回头看看。
Semaphore使用示例
先看下Semaphore原理图如下:
image.png
接着我们看下Redisson中使用的案例:
RSemaphore semaphore = redisson.getSemaphore("semaphore");
Semaphore源码解析
接着我们根据上面的示例,看看源码是如何实现的:
第一步:
semaphore.trySetPermits(3);
public class RedissonSemaphore extends RedissonExpirable implements RSemaphore {
@Override
public boolean trySetPermits(int permits) {
return get(trySetPermitsAsync(permits));
}
@Override
public RFuture 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.