秒杀案例
package com.atguigu.seckill.controller; 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.RequestMapping; import org.springframework.web.bind.annotation.RequestParam; import org.springframework.web.bind.annotation.RestController; import java.io.IOException; @RestController @RequestMapping("/seckill") public class SecKController { @Autowired private RedisTemplate redisTemplate; @GetMapping public String test(){ redisTemplate.opsForValue().set("name", "lucky"); String name = (String)redisTemplate.opsForValue().get("name"); System.out.println(name); return name; } //秒杀过程 @GetMapping("/getThing") public boolean getThing(@RequestParam String prodid){ String uid = new Random.nextInt(50000)+""; //1 uid和prodid非空判断 if(uid == null || prodid == null){ return false; } //2、拼接key //2.1 秒杀库存key String kcKey = "sk:" + prodid +":qt"; //2.2 秒杀成功用户key String userKey = "sk:" + prodid + ":user"; //3 获取库存,如果库存null,秒杀没有开始 Object kc = redisTemplate.opsForValue().get(kcKey); if(kc == null){ System.out.println("秒杀还没开始,请等待"); return false; } String kcnum = String.valueOf(kc); //4 判断用户是否重复秒杀操作 if(redisTemplate.opsForSet().isMember(userKey, uid)){ System.out.println("已经秒杀成功,不能重复秒杀"); return false; } //5 判断如果商品数量<=0,秒杀结束 if(Integer.parseInt(kcnum)<=0){ System.out.println("秒杀已结束"); return false; } //6 秒杀过程 //6.1 秒杀到,库存减一 redisTemplate.opsForValue().decrement(kcKey); //6.2 把秒杀成功用户添加到清单里面 redisTemplate.opsForSet().add(userKey, uid); System.out.println("秒杀成功了"); return true; } }
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 震惊!C++程序真的从main开始吗?99%的程序员都答错了
· 【硬核科普】Trae如何「偷看」你的代码?零基础破解AI编程运行原理
· 单元测试从入门到精通
· 上周热点回顾(3.3-3.9)
· winform 绘制太阳,地球,月球 运作规律