redis编写lua脚本实现商品秒杀
编写lua脚本
--是否秒杀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])
" +
"if hasBuy~=0 then
" +
"return 0;
" +
"end
"+
"for goodsIndex=2,#KEYS do
" +
" local goodStock = redis.call("get",KEYS[goodsIndex])
" +
" local redisStock=ARGV[goodsIndex]
"+
" if tonumber(goodStock) < tonumber(redisStock) 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";
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();
}
测试数据的话,自己手动加几条
redis.set(1001,100)redis.set(1002,100)
redis.set(1003,100)
已经秒杀的用户返回 0
秒杀成功返回 1
库存不足返回 2
参考:
https://blog.csdn.net/u010800970/article/details/81834965
https://blog.csdn.net/zhurhyme/article/details/79046470
以上是 redis编写lua脚本实现商品秒杀 的全部内容, 来源链接: utcz.com/z/510715.html