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
    );
相关推荐
MeAT ITEM1 天前
net.sf.jsqlparser.statement.select.Select.getSelectBody()
java
希望永不加班1 天前
SpringBoot 缓存一致性:缓存与数据库双写策略
数据库·spring boot·后端·缓存·oracle
我是无敌小恐龙1 天前
Java SE 零基础入门 Day02 运算符与流程控制超详细笔记
java·数据结构·spring boot·笔记·python·spring·spring cloud
invicinble1 天前
对于代码阅读能力的思考和总结
java
jrlong1 天前
HelloAgents 进阶篇 task03
java·前端·python
froginwe111 天前
Bootstrap4 导航栏
开发语言
虾神说D1 天前
[AI时代码农生存指南]Rust编写CLI 01. CLI的复古轮回
开发语言·人工智能·rust
Kurisu_红莉栖1 天前
c++的复习——多态
开发语言·c++
geovindu1 天前
go: Prototype Pattern
开发语言·设计模式·golang·原型模式
talen_hx2961 天前
飞书机器人发文本消息
java·前端·飞书