在springBoot项目中使用分布式锁,用redis实现
1.先定义一个lockKey
String lockKey="yys";
2.再定义一个随机数为了判断上锁和释放锁是否为同一个线程,解决因为线程阻塞,导致代码逻辑执行时间大于锁失效时间的情况,会存在释放锁是释放的其他线程的锁。
String uuid =UUID.randomUUID().toString();
3.使用StringRedisTemplate创建一把锁,返回true代表加锁成功,false代表失败
Boolean b =stringRedisTemplate.opsForValue().setIfAbsent(lockKey,uuid,10,TimeUnit.SECONDS); //jsdis.setNx();
这里设置过期时间一定要用这个方法保证原子性
不要以下这样写:
stringRedisTemplate.opsForValue().setIfAbsent(lockKey,uuid);
stringRedisTemplate.opsForValue().expire(lockKey, 10,TimeUnit.SECONDS);
4.要加finally块,在finally块里释放锁,释放自己上的锁
finally{
if(uuid.equals(stringRedisTemplate.opsForValue.get(lockKey))){
stringReidsTemplate.delete(lockKey);
}
}
以上都是伪代码,提供个思路,除大型互联网够用了,当然也可以使用redisson分布式锁。