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 }
hmoban主题是根据ripro二开的主题,极致后台体验,无插件,集成会员系统
自学咖网 » Redis锁相关