int result = stringRedisTemplate.execute(SECKILL_SCRIPT, //seckill.lua
Collections.emptyList(),
voucherId, userId, orderId
).intValue();
-- seckill.lua
-- 创建消息组 XGROUP CREATE stream.orders g1 0 MKSTREAM
-- 参数列表
local voucherId = ARGV[1] -- 优惠卷Id
local userId = ARGV[2] -- 用户ID
local orderId = ARGV[3] -- 订单ID
-- key列表
local stockKey = 'seckill:stock:' .. voucherId; -- 库存key
local orderKey = 'seckill:order' .. voucherId; -- 订单key
-- 脚本业务
-- 判断库存是否充足 get stockKey
if (tonumber(redis.call('get', stockKey)) >= 0) then
return 1; -- 库存不足返回1
end
-- 判断用户是否已下单 get orderKey
if (redis.call('sismember', orderKey, userId) == 1) then
return 2; -- 已下单返回2
end
-- 扣库存 incrby stockKey -1
redis.call('incrby', stockKey, -1);
-- 下单 sadd orderKey userId
redis.call('sadd', orderKey, userId);
-- 发送消息到队列中,xadd stream.orders * k1 v1 ……
redis.call('xadd', 'stream.orders', '*', 'userId', userId, 'voucherId', voucherId, 'id', orderId);
return 0;
-- unlock.lua
-- 比较线程标识与锁中的标识是否一致
if(redis.call('GET',KEYS[1]) == ARGV[1]) then
--释放锁
return redis.call('DEL',KEYS[1])
end
return 0
-- 可重入锁getlock.lua,单体架构
local key = KEYS[1];
local threadId = ARGV[1];
local releaseTime = ARGV[2]; --自动过期时间
--判断锁是否存在
if (redis.call('exists', key) == 0) then
-- 创建锁
redis.call('hset', key, threadId, '1');
-- 设置存活时间
redis.call('expire', key, releaseTime);
return 1;
end ;
-- 存在则判断threadId是否是自己
if (redis.call('hexists', key, threadId) == 1) then
-- 获取锁,锁重入次数+1
redis.call('hincrby', key, threadId, 1);
-- 重新设置存活时间
redis.call('expire', key, releaseTime);
return 1;
end ;
return 0; --说明锁不是自己的,获取锁失败
-- 可重入解锁unlock.lua
local key = KEYS[1];
local threadId = ARGV[1];
local releaseTime = ARGV[2]; --自动过期时间
-- 判断锁是不是自己的
if (redis.call('hexists', key, threadId) == 0) then
return null;
end ;
-- 锁是自己的,锁重入次数减一
local count = redis.call('hincrby', key, threadId, -1);
-- 判断锁重入次数是否已经为0
if (count > 0) then
-- 大于0说明不能释放锁,重新设置存活时间
redis.call('expire', key, releaseTime);
return nil;
else
--可以释放锁
redis.call('del', key);
return nil;
end ;