Redis使用lua脚本

用lua脚本使用redis是为了保证其原子性和线程安全。

step1:编写lua脚本,放在resource中

step2:创建脚本对象,这里因为脚本对象是静态的所以在静态代码块中进行构造

  • setLocation: 这里的 ClassPathResource 会从类路径(通常是 resources 文件夹)读取文件。

  • setResultType(Long.class): 对应 Lua 脚本最后的 return

step3:执行lua脚本

复制代码
RedisScript<T> script脚本对像
Keys 输入Key数组参数
args 输入args数组参数
java 复制代码
private static final DefaultRedisScript<Long> UNLOCK_SCRIPT;
static {
    UNLOCK_SCRIPT = new DefaultRedisScript<>();
    UNLOCK_SCRIPT.setLocation(new ClassPathResource("unlock.lua"));
    UNLOCK_SCRIPT.setResultType(Long.class);
}

public void unlock() {
    // 调用lua脚本
    stringRedisTemplate.execute(
            UNLOCK_SCRIPT,
            Collections.singletonList(KEY_PREFIX + name),
            ID_PREFIX + Thread.currentThread().getId());
}
相关推荐
胡利光1 小时前
Harness Engineering 02|Repo Harness:让仓库对 Agent 可读
java·junit·单元测试
Elastic 中国社区官方博客2 小时前
使用 EDOT Browser 和 Kibana 进行 OpenTelemetry 浏览器端埋点
大数据·服务器·数据库·elasticsearch·搜索引擎·单元测试·可用性测试
绿草在线11 小时前
SpringBoot请求与响应全解析
spring boot·后端·lua
姚青&11 小时前
软件测试基础概念
单元测试·pytest
上海合宙LuatOS1 天前
LuatOS扩展库API——【libnet】TCP/UDP协议
物联网·tcp/ip·junit·udp·luatos
心之所向,自强不息1 天前
VSCode + EmmyLua 调试 Unity Lua(最简接入 + 不阻塞运行版)
vscode·unity·lua
川石课堂软件测试1 天前
技术分享|JMeter接口与性能测试实战
数据库·功能测试·测试工具·jmeter·单元测试·postman·prometheus
weixin_408099671 天前
Lua请求文字识别ocr api
图像处理·人工智能·后端·ocr·lua·api·文字识别
上海合宙LuatOS2 天前
LuatOS扩展库API——【libfota】远程升级
物联网·junit·lua·luatos
上海合宙LuatOS2 天前
LuatOS扩展库API——【libfota2】远程升级
网络·物联网·junit·luatos