背景
在秒杀服务中,库存一般是放在redis缓存中的,这里有一个信号量工具,类似于GUC中的CountDownLatch 人走关门的那个列子。
@Autowired
private RedissonClient redissonClient;
/**
* redis 信号量的使用,类似与JUC中的人走了关门那个工具类
* 设置一个总数为10的信号量
*/
@Test
public void redisXihaoliang(){
// 使用库存作为分布式信号量
RSemaphore semaphore = redissonClient.getSemaphore("xinhaoliang");
// 商品可以秒杀的数量作为信号量
semaphore.trySetPermits(10);
}
/**
* 消费信号量
* @throws InterruptedException
*/
@Test
public void redisXiaofei() throws InterruptedException {
// 使用库存作为分布式信号量
RSemaphore semaphore = redissonClient.getSemaphore("xinhaoliang");
// 商品可以秒杀的数量作为信号量
boolean acquire = semaphore.tryAcquire(1, 100, TimeUnit.MILLISECONDS);
if(acquire){
System.out.println("maruis------>" + "扣减成功");
}else{
System.out.println("maruis------>" + "没有库存了");
}
}