Redis锁相关

Redis锁相关

 

    君不见,高堂明镜悲白发,朝如青丝暮成雪。

 

背景:面试的时候被问到有哪些锁,很快脱口而出Volatile、Synchronized和ReentrantLock,也能讲出他们之间的一些区别;当问到如在同一服务下同步锁可以起作用,但是在不同的服务器上部署同一个微服务工程,然后用nginx作代理,很明显,现在的线程锁不管用了。分布式情况下如何保证线程同步?当时就答不上来了,分布式环境下我们需要换一把锁,这把锁必须和两套甚至多套系统没有任何的耦合度。可以使用Redis锁实现分布式场景下的线程同步,使用Redies的API,如果key不存在,则设置一个key,这个key就是我们现在使用的一把锁。每个线程到此处,先设置锁,如果设置锁失败,则表明当前有线程获取到了锁,就返回。

一、单一服务器下的锁

例如将商品的数量存到Redis中。每个用户抢购前都需要到Redis中查询商品数量(代替mysql数据库。不考虑事务),如果商品数量大于0,则证明商品有库存;然后我们在进行库存扣减和接下来的操作;因为多线程并发问题,我们还需要在get()方法内部使用同步代码块,保证查询库存和减库存操作的原子性。

 1 import lombok.AllArgsConstructor;
 2 import lombok.extern.slf4j.Slf4j;
 3 import org.springframework.data.redis.core.RedisTemplate;
 4 import org.springframework.web.bind.annotation.GetMapping;
 5 import org.springframework.web.bind.annotation.RequestHeader;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.RestController;
 8 
 9 @RestController
10 @AllArgsConstructor
11 @RequestMapping("/redis")
12 @Slf4j
13 public class TryRedisLock {
14 
15     private RedisTemplate<String, String> redisTemplate;
16 
17     @GetMapping(value = "/try/buy")
18     public String get(@RequestHeader(required = false) String userId) {
19         synchronized (this) {  // 单机同步
20             String bird = redisTemplate.opsForValue().get("bird");
21             Integer count = Integer.valueOf(bird);
22             if (count > 0) {
23                 // 减库存
24                 redisTemplate.opsForValue().set("bird", String.valueOf(count - 1));
25                 log.info("用户{}, 抢到了, {} 号商品!", userId, bird);
26             }
27             return "零库存";
28         }
29     }
30 }
View Code

二、分布式场景redis锁

分布式场景下使用redis锁需要注意如下几个问题:

  • 一台服务器宕机,导致无法释放锁;可以在try-catch的finally中释放锁或者给每一把锁加过期时间。
  • 任务线程未执行完毕但锁已失效;可以延长锁的过期时间,使用定时器防止key过期。
  • 使用Redisson框架简化代码;getLock()方法代替了Redis的setIfAbsent()lock()设置过期时间,最终我们在交易结束后释放锁;延长锁的操作则由Redisson框架替我们完成,它会使用轮询去查看key是否过期,在交易没有完成时,自动重设Redis的key过期时间。
 1 import lombok.AllArgsConstructor;
 2 import lombok.extern.slf4j.Slf4j;
 3 import org.springframework.data.redis.core.RedisTemplate;
 4 import org.springframework.web.bind.annotation.GetMapping;
 5 import org.springframework.web.bind.annotation.RequestHeader;
 6 import org.springframework.web.bind.annotation.RequestMapping;
 7 import org.springframework.web.bind.annotation.RestController;
 8 
 9 @RestController
10 @AllArgsConstructor
11 @RequestMapping("/redis")
12 @Slf4j
13 public class TryRedisLock {
14 
15     private RedisTemplate<String, String> redisTemplate;
16 
17 
18     @GetMapping(value = "/try/again/buy")
19     public String getJudge(@RequestHeader(required = false) String userId) {
20         // 每个线程到此处,先设置锁
21         /**
22          * 使用Redies的API如果key不存在,则设置一个key。这个key就是我们现在使用的一把锁
23          * 每个线程到此处,先设置锁
24          * 如果设置锁失败,则表明当前有线程获取到了锁,就返回。
25          */
26         Boolean birdLock = redisTemplate.opsForValue().setIfAbsent("birdLock", "");
27         if (!birdLock) {
28             return "";
29         }
30         try {
31             String bird = redisTemplate.opsForValue().get("bird");
32             Integer count = Integer.valueOf(bird);
33             if (count > 0) {
34                 redisTemplate.opsForValue().set("bird", String.valueOf(count - 1));
35                 log.info("用户{}, 抢到了, {} 号商品!", userId, bird);
36             }
37         } finally {
38             redisTemplate.delete("birdLock");  // 删除锁
39         }
40         return "";
41     }
42 
43     @GetMapping(value = "/try/buy")
44     public String get(@RequestHeader(required = false) String userId) {
45         synchronized (this) {  // 单机同步
46             String bird = redisTemplate.opsForValue().get("bird");
47             Integer count = Integer.valueOf(bird);
48             if (count > 0) {
49                 // 减库存
50                 redisTemplate.opsForValue().set("bird", String.valueOf(count - 1));
51                 log.info("用户{}, 抢到了, {} 号商品!", userId, bird);
52             }
53             return "零库存";
54         }
55     }
56 }
View Code

 

 

 

 

君不见

         高堂明镜悲白发

          朝如青丝暮成雪

 

 

 

 

posted @ 2021-09-14 09:23  涛姐涛哥  阅读(237)  评论(0编辑  收藏  举报