lua脚本保证多条命令原子性

这里使用一个例子,实现下图功能

步骤一:在resource目录下定义lua脚本

Lua 复制代码
local voucherId = ARGV[1]
-- 1.2.用户id
local userId = ARGV[2]


-- 2.数据key
-- 2.1.库存key
local stockKey = 'seckill:stock:' .. voucherId
-- 2.2.订单key
local orderKey = 'seckill:order:' .. voucherId

-- 3.脚本业务
-- 3.1.判断库存是否充足 get stockKey
if(tonumber(redis.call('get', stockKey)) <= 0) then
    -- 3.2.库存不足,返回1
    return 1
end
-- 3.2.判断用户是否下单 SISMEMBER orderKey userId
if(redis.call('sismember', orderKey, userId) == 1) then
    -- 3.3.存在,说明是重复下单,返回2
    return 2
end
-- 3.4.扣库存 incrby stockKey -1
redis.call('incrby', stockKey, -1)
-- 3.5.下单(保存用户)sadd orderKey userId
redis.call('sadd', orderKey, userId)
return 0

步骤二:在使用的类里常见脚本并配置

java 复制代码
private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
    static {
        UNLOCK_SCRIPT = new DefaultRedisScript<>();
        UNLOCK_SCRIPT.setLocation(new ClassPathResource("voucher.lua")); //设置lua脚本的位置
        UNLOCK_SCRIPT.setResultType(Long.class); //返回值
    }

步骤三:调用脚本

java 复制代码
    Long result = stringRedisTemplate.execute(
            SECKILL_SCRIPT,
            Collections.emptyList(), //KEYS
            voucherId.toString(), userId.toString()//ARGV
    );
相关推荐
IT19951 分钟前
IDEA+JDK11编译SpringCore5源码及替换项目中的Springcore
java·ide·intellij-idea
techzhi1 分钟前
IntelliJ IDEA 启动卡顿问题排查与解决
java·ide·intellij-idea
m0_748250032 分钟前
C++ 修饰符类型
开发语言·c++
WayneJoon.H5 分钟前
2023CISCN deserbug复现
java·安全·web安全·cc链·反序列化
week_泽5 分钟前
第8课:LangGraph Memory管理机制与实现方案 - 学习笔记_8
java·笔记·学习·ai agent
李日灐7 分钟前
C++STL:仿函数、模板(进阶) 详解!!:“伪装术”和模板特化、偏特化的深度玩法指南
开发语言·c++·后端·stl
rgeshfgreh11 分钟前
Python连接KingbaseES数据库全指南
开发语言·数据库·python
装不满的克莱因瓶16 分钟前
【cursor】前后端分离项目下的AI跨工程管理方案
java·人工智能·ai·ai编程·cursor·trae·qoder
Wang's Blog17 分钟前
Nodejs-HardCore: 玩转 EventEmitter 指南
开发语言·nodejs
何中应19 分钟前
使用Spring自带的缓存注解维护数据一致性
java·数据库·spring boot·后端·spring·缓存