基于Redis setNX命令实现分布式加解锁
2021/10/12 2:14:28
本文主要是介绍基于Redis setNX命令实现分布式加解锁,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
1、setNX命令说明: SET resource_name my_random_value NX PX 30000 2、代码演示: @Service public class BaseSetNXDistributeLockService { private static final Logger LOGGER = LoggerFactory.getLogger(BaseSetNXDistributeLockService.class); @Autowired private RedisTemplate redisTemplate; public String redisLock() { LOGGER.info("我进入了方法!"); String key = "redisKey"; String value = UUID.randomUUID().toString(); RedisCallback<Boolean> redisCallback = connection -> { //设置NX RedisStringCommands.SetOption setOption = RedisStringCommands.SetOption.ifAbsent(); //设置过期时间 Expiration expiration = Expiration.seconds(30); //序列化key byte[] redisKey = redisTemplate.getKeySerializer().serialize(key); //序列化value byte[] redisValue = redisTemplate.getValueSerializer().serialize(value); //执行setnx操作 Boolean result = connection.set(redisKey, redisValue, expiration, setOption); return result; }; //获取分布式锁 Boolean lock = (Boolean) redisTemplate.execute(redisCallback); if (lock) { LOGGER.info("我进入了锁!"); try { Thread.sleep(15000); } catch (InterruptedException e) { e.printStackTrace(); } finally { String script = "if redis.call(\"get\",KEYS[1]) == ARGV[1] then\n"+ " return redis.call(\"del\",KEYS[1])\n"+ "else\n"+ " return 0\n"+ "end"; RedisScript<Boolean> redisScript = RedisScript.of(script, Boolean.class); List<String> keys = Arrays.asList(key); Boolean result = (Boolean) redisTemplate.execute(redisScript,keys,value); LOGGER.info("释放锁的结果:"+result); } } return "方法执行完成!"; } }
这篇关于基于Redis setNX命令实现分布式加解锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-11-08阿里云Redis项目实战入门教程
- 2024-11-08阿里云Redis资料:新手入门与初级使用指南
- 2024-11-08阿里云Redis教程:新手入门及实用指南
- 2024-11-07阿里云Redis学习入门:新手必读指南
- 2024-11-07阿里云Redis学习入门:从零开始的操作指南
- 2024-11-07阿里云Redis学习:初学者指南
- 2024-11-06阿里云Redis入门教程:轻松搭建与使用指南
- 2024-11-02Redis项目实战:新手入门教程
- 2024-10-22Redis入门教程:轻松掌握数据存储与操作
- 2024-10-22Redis缓存入门教程:快速掌握Redis缓存基础知识