一、使用redis实现分布式锁
spirngboot使用redis:SpringBoot2.4.5使用redis缓存
@Autowired RedisTemplate redisTemplate; void test01() { String localKey = "lock01"; //设置当前客户端ID String clentId = UUID.randomUUID().toString(); try { //判断localKey是否存在,如果不存在,设置值,如果存在,不执行任务 Boolean aBoolean = redisTemplate.opsForValue().setIfAbsent(localKey, clentId, 10, TimeUnit.SECONDS); if (!aBoolean) { return; } // 执行操作,子线程自动续期localKey的过期实践 } finally { //避免A客户端,删除B客户端设置的锁 if (clentId.equals(redisTemplate.opsForValue().get(localKey))) { //释放锁 redisTemplate.delete(localKey); } } }
二、使用Redisson实现分布式锁
springboot使用redisson:springboot使用redisson
@Autowired Redisson redisson; @Test void test02() { String localKey = "lock01"; RLock lock = redisson.getLock(localKey); try { lock.lock(); } finally { lock.unlock(); } }