前言
网上很多都是jedis客户端的形式实现分布式锁,没有redisTemplate形式的实现,而且众说纷杂有很多不合理的地方。实现思路是从我的参考博客仿照写的,讲的很清楚了,大家可以去我得参考博客看。这是相对较为完美的方案,并不是最完美的。spring-data-redis的版本尽量高版本,2.0以下的connection.set是没有返回值的,我用的是下面的依赖,这里提一下。下面不多说直接放代码,很简短。
依赖
<dependency>
<groupId>org.springframework.data</groupId>
<artifactId>spring-data-redis</artifactId>
<version>2.0.9.RELEASE</version>
</dependency>
代码
@Component
public class RedisDistributedLock {
@Resource
private RedisTemplate<String, Object> redisTemplate;
public synchronized boolean lock(String key, String requestId, long expire) {
return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
Boolean result = connection.set(key.getBytes(), requestId.getBytes(), Expiration.from(expire, TimeUnit.SECONDS), RedisStringCommands.SetOption.SET_IF_ABSENT);
return result;
});
}
public synchronized boolean releaseLock(String key, String requestId) {
return (Boolean) redisTemplate.execute((RedisCallback) connection -> {
String script = "if redis.call('get', KEYS[1]) == ARGV[1] then return redis.call('del', KEYS[1]) else return 0 end";
Boolean result = connection.eval(script.getBytes(), ReturnType.BOOLEAN, 1, key.getBytes(), requestId.getBytes());
return result;
});
}
}
我的参考博客:
https://www.cnblogs.com/linjiqin/p/8003838.htmlhttps://mp.weixin.qq.com/s?__biz=MzI1NDQ3MjQxNA==&mid=2247486626&idx=1&sn=f8b410dd4d406bdc68c0a063d48b78a3&chksm=e9c5f513deb27c05fc4962b01fea54310dd93447fe7cc260c31eb10ac4e9a0b72f0b61f79820&mpshare=1&scene=1&srcid=1228Iy5C0eFGMtDS3eU98LBU#rd
https://blog.csdn.net/u014677702/article/details/83308972
https://www.cnblogs.com/liuyang0/p/6800538.html
http://www.hollischuang.com/archives/1716