编写lua脚本redis
--是否秒杀 local hasBuy = redis.call('sismember',KEYS[1],ARGV[1]) if hasBuy~=0 then return 0; end --校验库存 for goodsIndex=2,#KEYS do local goodStock = redis.call('get',KEYS[goodsIndex]) if tonumber(goodStock) < tonumber(ARGV[goodsIndex]) then return 2; end end --扣库存 for goodsIndex=2,#KEYS do redis.call('decrby',KEYS[goodsIndex],ARGV[goodsIndex]) end --抢单成功 redis.call('sadd',KEYS[1],ARGV[1]) return 1
测试用例测试
Jedis jedis = jedisPool.getResource(); jedis.select(2); String luaStr = "local hasBuy = redis.call('sismember',KEYS[1],ARGV[1])\n" + "if hasBuy~=0 then\n" + "return 0;\n" + "end \n"+ "for goodsIndex=2,#KEYS do\n" + " local goodStock = redis.call('get',KEYS[goodsIndex])\n" + " local redisStock=ARGV[goodsIndex]\n"+ " if tonumber(goodStock) < tonumber(redisStock) then\n" + " return 2;\n" + " end\n" + "end\n"+ "for goodsIndex=2,#KEYS do\n" + "redis.call('decrby',KEYS[goodsIndex],ARGV[goodsIndex])\n" + "end\n"+ "redis.call('sadd',KEYS[1],ARGV[1])\n" + "return 1"; List<String> keys = new ArrayList<>(); keys.add("user_id"); //商品ID keys.add("1001"); keys.add("1002"); keys.add("1003"); List<String> values = new ArrayList<>(); values.add(userId); //商品购买量 values.add(goodsNums.get(0)); values.add(goodsNums.get(1)); values.add(goodsNums.get(2)); Object result = jedis.eval(luaStr, keys,values); System.out.println("redis返回 result: " + result); if (jedis != null) { jedis.close(); }
测试数据的话,本身手动加几条lua
redis.set(1001,100) redis.set(1002,100) redis.set(1003,100)
已经秒杀的用户返回 0 .net
秒杀成功返回 1code
库存不足返回 2blog
参考:get
https://blog.csdn.net/u010800970/article/details/81834965List
https://blog.csdn.net/zhurhyme/article/details/79046470select