redis单机部署时实现的分布式锁
2021/8/25 19:06:30
本文主要是介绍redis单机部署时实现的分布式锁,对大家解决编程问题具有一定的参考价值,需要的程序猿们随着小编来一起学习吧!
redis单机部署时实现的分布式锁
/** * @Author: zqf * @Description: * @Date 2021/8/25 10:08 */ public class DistributedLock { /** * 释放锁lua脚本,原子操作:lua脚本是作为一个整体执行的,所以中间不会被其他命令插入。 */ private final static String RELEASE_LOCK_LUA_SCRIPT = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end"; private static final Long RELEASE_SUCCESS = 1L; /** * * @param lockId 锁 * @param requestId 请求标识 * @param seconds 过期时间 * @return */ public static boolean getLock(RedisTemplate redisTemplate, String lockId, String requestId, long seconds) { Boolean success = redisTemplate.opsForValue().setIfAbsent(lockId, requestId, seconds, TimeUnit.SECONDS); return success != null && success; } /** * 释放锁 * @param redisTemplate * @param lockId 锁 * @param requestId 请求标识 * @return 是否释放成功 */ public static boolean releaseLock(RedisTemplate redisTemplate, String lockId, String requestId) { // 指定 lua 脚本,并且指定返回值类型 DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(RELEASE_LOCK_LUA_SCRIPT,Long.class); // 参数一:redisScript,参数二:key列表,参数三:arg(可多个) Long result = (Long) redisTemplate.execute(redisScript, Collections.singletonList(lockId), requestId); return RELEASE_SUCCESS.equals(result); } }
这篇关于redis单机部署时实现的分布式锁的文章就介绍到这儿,希望我们推荐的文章对大家有所帮助,也希望大家多多支持为之网!
- 2024-03-21redisinsight-v2
- 2024-02-26Typed property App\Api\Mapper\GamePropsConfigMapper::$apiRedis must not be accessed before initia-icode9专业技术文章分享
- 2024-02-21redisson getlock
- 2024-02-20redis config
- 2024-02-20redis leaderboard
- 2024-01-23缓存选型:Redis or MemCache
- 2024-01-22面试官:Redis持久化能关吗?怎么关?
- 2024-01-21Redis压测工具redis-benchmark-icode9专业技术文章分享
- 2024-01-19这才是你应该了解的Redis数据结构!
- 2024-01-18Redis系列:使用 Redis Module 扩展功能