編寫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