Java爬坑--stringRedisTemplate 分布式锁双重检测

1.查询缓存,如果缓存存在,返回结果

 

2.缓存不存在,查询数据库

 

3.争夺分布式锁

 

4.成功获得锁,再次判断缓存的存在

 

5.如果缓存仍旧不存在,把查询数据库的结果循环放入缓存

 

6.释放分布式锁

 

 1      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     }

还没测试.....

posted @ 2018-01-09 11:42  杨康是个大坏蛋  阅读(878)  评论(0编辑  收藏  举报