RedisTemplate实现分布式锁
使用RedisTemplate的execute的回调方法,里面使用Setnx方法
Setnx
就是,如果没有这个key
,那么就set一个key-value, 但是如果这个key
已经存在,那么将不会再次设置,get出来的value还是最开始set进去的那个value.
接下来我们用代码的形式展现:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
|
import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisCallback; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.data.redis.core.ValueOperations; import org.springframework.stereotype.Component; import java.util.Objects; import java.util.concurrent.TimeUnit; /** * Description: 通用Redis帮助类 * User: zhouzhou * Date: 2018-09-05 * Time: 15:39 */ @Component public class CommonRedisHelper { //锁名称 public static final String LOCK_PREFIX = "redis_lock" ; //加锁失效时间,毫秒 public static final int LOCK_EXPIRE = 300 ; // ms @Autowired RedisTemplate redisTemplate; /** * 最终加强分布式锁 * * @param key key值 * @return 是否获取到 */ public boolean lock(String key){ String lock = LOCK_PREFIX + key; // 利用lambda表达式 return (Boolean) redisTemplate.execute((RedisCallback) connection -> { long expireAt = System.currentTimeMillis() + LOCK_EXPIRE + 1 ; Boolean acquire = connection.setNX(lock.getBytes(), String.valueOf(expireAt).getBytes()); if (acquire) { return true ; } else { byte [] value = connection.get(lock.getBytes()); if (Objects.nonNull(value) && value.length > 0 ) { long expireTime = Long.parseLong( new String(value)); // 如果锁已经过期 if (expireTime < System.currentTimeMillis()) { // 重新加锁,防止死锁 byte [] oldValue = connection.getSet(lock.getBytes(), String.valueOf(System.currentTimeMillis() + LOCK_EXPIRE + 1 ).getBytes()); return Long.parseLong( new String(oldValue)) < System.currentTimeMillis(); } } } return false ; }); } /** * 删除锁 * * @param key */ public void delete(String key) { redisTemplate.delete(key); } |
如何使用呢,导入工具类后:
CommonRedisHelper redisHelper = new CommonRedisHelper();
1
|
boolean lock = redisHelper.lock(key); |
if (lock) { // 执行逻辑操作 redisHelper.delete(key); } else { // 设置失败次数计数器, 当到达5次时, 返回失败 int failCount = 1; while(failCount <= 5){ // 等待100ms重试 try { Thread.sleep(100l); } catch (InterruptedException e) { e.printStackTrace(); } if (redisHelper.lock(key)){ // 执行逻辑操作 redisHelper.delete(key); }else{ failCount ++; } } throw new RuntimeException("现在创建的人太多了, 请稍等再试"); }
版权保护: 本文由 佳云博客 原创,转载请保留链接: https://www.garyun.com/gan/168.html
站长推荐: 爱诺伊影视|高清电影|热门美剧: 高清电影在线观看
热门文章
-
Java,Calendar -- 获取当前日期、当月月初日期、月末 2020/07/30
-
RedisTemplate实现分布式锁 2020/07/30
-
CentOS 7 通过Yum方式PHP 7安装步骤 2020/07/28
-
Linux关机执行脚本命令应该怎么做? 2020/07/28
-
如何获取微信二维码名片的地址? 2020/07/28
-
linux删除大量文件命令和效率对比 2020/07/27
-
dedecms网站如何修改上一篇下一篇的标题字数 2020/07/27
-
织梦DEDE自带采集标题限制,解决文章标题字数长度 2020/07/27