1.查询缓存,如果缓存存在,返回结果
2.缓存不存在,查询数据库
3.争夺分布式锁
4.成功获得锁,再次判断缓存的存在
5.如果缓存仍旧不存在,把查询数据库的结果循环放入缓存
6.释放分布式锁
复制代码
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
76
77
78
79
80
81
82
83
84
851 public List getCouponList(String key){ 2 3 String lockKey = generateLockKey(key); 4 5 6 // 如果优惠券列表在缓存中存在,从缓存查取 7 if(stringRedisTemplate.hasKey(key)){ 8 return stringRedisTemplate.boundListOps(key).range(0, -1); 9 } 10 // 缓存不存在,从DB查询 11 List<String> couponList = getCouponListFromDB(key); 12 // 争夺分布式锁,过期时间1秒 13 if(stringRedisTemplate.getConnectionFactory().getConnection().setNX(lockKey.getBytes(),new byte[0])){ 14 stringRedisTemplate.expire(lockKey, 1, TimeUnit.SECONDS);//暂设置为1s过期 15 try { 16 // 如果优惠券列表在缓存中存在,从缓存查取(再次判断) 17 if(stringRedisTemplate.hasKey(key)){ 18 return stringRedisTemplate.boundListOps(key).range(0, -1); 19 } 20 // 将查出来的数据放入缓存 21 for (String coupon : couponList) { 22 stringRedisTemplate.boundListOps(key).leftPush(coupon); 23 } 24 } catch (Exception e) { 25 e.printStackTrace(); 26 unlock(key); 27 }finally { 28 unlock(key); 29 } 30 } 31 32 return couponList; 33 } 34 private String generateLockKey(String key) { 35 String REDIS_LOCK = "String RedisLock:"; 36 return String.format(REDIS_LOCK + "%s", key); 37 } 38 39 public void unlock(String key) { 40 String lockKey = generateLockKey(key); 41 42 RedisConnection connection = stringRedisTemplate.getConnectionFactory().getConnection(); 43 connection.del(lockKey.getBytes()); 44 connection.close(); 45 }
还没测试.....
转载于:https://www.cnblogs.com/chuzihang/p/8250680.html
最后
以上就是沉默星星最近收集整理的关于Java爬坑--stringRedisTemplate 分布式锁双重检测的全部内容,更多相关Java爬坑--stringRedisTemplate内容请搜索靠谱客的其他文章。
本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
发表评论 取消回复