场景:一家网上商城做商品限量秒杀。

1 单机环境下的锁

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

package springbootdemo.demo.controller;
/*
 * @auther 顶风少年
 * @mail dfsn19970313@foxmail.com
 * @date 2020-01-13 11:19
 * @notify
 * @version 1.0
 */

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class RedisLock  {

    @Autowired
    private RedisTemplate<String, String> redisTemplate;

    @GetMapping(value = "buy")
    public String get() {
        synchronized (this) {
            String phone = redisTemplate.opsForValue().get("phone");
            Integer count = Integer.valueOf(phone);
            if (count > 0) {
                redisTemplate.opsForValue().set("phone", String.valueOf(count - 1));
                System.out.println("抢到了" + count + "号商品");
            }return "";
        }
    }
}
View Code

相关文章: