@RestController public class HelloWorld { @GetMapping("hello") public Result hello(){ Integer uid = (int) (Math.random()*100); String userKey = "sk:1010:user"; String kcKey = "sk:1010:qt"; Jedis jedis = new Jedis("42.193.140.45", 6379); if(jedis.get(kcKey) == null){ System.out.println("秒杀未开始"); jedis.close(); return Result.fail(); } //判断是否重复秒杀 if(jedis.sismember(userKey,uid.toString())){ System.out.println("你已经秒杀了,不能重复秒杀"); jedis.close(); return Result.fail(); } if(Integer.parseInt(jedis.get(kcKey))<=0){ System.out.println("秒杀结束"); jedis.close(); return Result.fail(); } jedis.decr(kcKey); jedis.sadd(userKey,uid.toString()); System.out.println("秒杀成功"); jedis.close(); return Result.ok(); } @GetMapping("init") public Result init(){ String userKey = "sk:1010:user"; Jedis jedis = new Jedis("42.193.140.45", 6379); jedis.set("sk:1010:qt","10"); jedis.del(userKey); jedis.close(); return Result.ok(); } @GetMapping("info") public Result info(){ Jedis jedis = new Jedis("42.193.140.45", 6379); Set<String> smembers = jedis.smembers("sk:1010:user"); System.out.println(smembers); String s = jedis.get("sk:1010:qt"); System.out.println(s); return Result.ok(); } }
并发 执行之后会出现负值
1. 添加乐观锁
public Result hello(){ Integer uid = (int) (Math.random()*100); String userKey = "sk:1010:user"; String kcKey = "sk:1010:qt"; Jedis jedis = new Jedis("42.193.140.45", 6379); //1 添加监视 jedis.watch(kcKey); if(jedis.get(kcKey) == null){ System.out.println("秒杀未开始"); jedis.close(); return Result.fail(); } //判断是否重复秒杀 if(jedis.sismember(userKey,uid.toString())){ System.out.println("你已经秒杀了,不能重复秒杀"); jedis.close(); return Result.fail(); } if(Integer.parseInt(jedis.get(kcKey))<=0){ System.out.println("秒杀结束"); jedis.close(); return Result.fail(); } //2 开启事务 Transaction multi = jedis.multi(); //3 组队 multi.decr(kcKey); //jedis.decr(kcKey); //jedis.sadd(userKey,uid.toString()); multi.sadd(userKey,uid.toString()); //4 执行 List<Object> exec = multi.exec(); if(exec == null || exec.size() == 0){ System.out.println("秒杀失败"); jedis.close(); return Result.fail(); } System.out.println("秒杀成功"); jedis.close(); return Result.ok(); }
结果:
标签:实现,System,乐观,秒杀,Result,println,jedis,out From: https://www.cnblogs.com/cciscc/p/16873432.html