高併發下防止商品超賣的Redis實現
阿新 • • 發佈:2018-11-19
@RestController @RequestMapping("/rushbuy") @Slf4j public class RushbuyController { @Autowired private RedisTemplate redisTemplate; //釋出搶購,初始庫存 @PutMapping("/save/good/data") public void save() { int aaSkuNum = 100; redisTemplate.opsForList().trim("aaSku:num", -1, 0); List<Integer> skuList = new ArrayList<>(); for (int i = 1; i <= aaSkuNum; i++) { skuList.add(i); } redisTemplate.opsForList().rightPushAll("aaSku:num", skuList); List list = redisTemplate.opsForList().range("aaSku:num", 0, -1); log.info("list = {}", list.toString()); } //搶購 @GetMapping("/buy") public void buy() { Object goods = redisTemplate.opsForList().leftPop("aaSku:num"); log.info("leftPop = {}", goods); if (goods == null) { log.info("秒殺失敗(無庫存)..."); }else{ int num = new Random().nextInt(1000) + 1; Long result = redisTemplate.opsForSet().add("candidate:userids", num); if (result > 0) { log.info("成功秒殺"); } else { System.out.println("重複下單 :::::: " + num); redisTemplate.opsForList().rightPush("sku:awards", 1); } } } }
Swagger-UI往redis中初始庫存
Jmeter多執行緒模擬購買