Spring Boot - 结合 Redis 使用 Lua脚本

在Spring Boot中整合Redis并使用Lua脚本:

  1. 添加Spring Boot和Redis的依赖:

首先,在Spring Boot项目的pom.xml文件中添加Spring Boot和Spring Data Redis的依赖:

复制代码
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-data-redis</artifactId>
</dependency>
  1. 配置Redis连接:

在application.properties或application.yml中配置Redis的连接信息,以及 redis 配置:

复制代码
server:
  port: 8080

spring:
  redis:
    host: localhost
    port: 6379

RedisConfig.java

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.GenericJackson2JsonRedisSerializer;
import org.springframework.data.redis.serializer.StringRedisSerializer;

@Configuration
public class RedisConfig {

    @Bean
    public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        RedisTemplate<String, Object> template = new RedisTemplate<>();
        template.setConnectionFactory(redisConnectionFactory);

        // 设置键的序列化方式为String
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());

        // 设置值的序列化方式为JSON
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());

        template.afterPropertiesSet(); // 必须调用该方法,完成初始化

        return template;
    }
}
  1. 创建一个Spring服务来执行Lua脚本
    在src/main/resources/ 下创建 scripts/incrementBy.lua,这样,在外部文件中维护Lua脚本,并在需要时加载并执行它。这种方法更容易维护和管理复杂的Lua脚本,同时还提供了更好的可读性。确保在加载脚本文件时处理可能的异常。
java 复制代码
-- src/main/resources/scripts/incrementBy.lua
local key = KEYS[1]               -- 获取第一个参数作为键名
local incrementBy = tonumber(ARGV[1])  -- 获取第二个参数作为增量值,并将其转换为数字类型

-- 存储key和incrementBy的值:仅作debug用
-- redis.call("SET", "debug_key", key)
-- redis.call("SET", "debug_incrementBy", incrementBy)

local currentValue = redis.call("GET", key)  -- 通过GET命令获取键的当前值
if not currentValue then
    currentValue = 0  -- 如果键不存在,将当前值初始化为0
else
    currentValue = tonumber(currentValue)  -- 如果键存在,将当前值转换为数字类型
end

local newValue = currentValue + incrementBy  -- 计算新的值
redis.call("SET", key, newValue)  -- 通过SET命令将新值存储到键中

return newValue  -- 返回新值

创建一个服务类,用于执行Lua脚本:

复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.io.ClassPathResource;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.script.DefaultRedisScript;
import org.springframework.stereotype.Service;

import java.io.IOException;
import java.nio.file.Files;
import java.util.Collections;

@Service
public class RedisLuaService {

    @Autowired
    private RedisTemplate<String, Object> redisTemplate;

    public Long executeLuaScript(String key, long incrementBy) {
        ClassPathResource luaScriptResource = new ClassPathResource("scripts/incrementBy.lua");
        String luaScript;

        try {
            luaScript = new String(Files.readAllBytes(luaScriptResource.getFile().toPath()));
        } catch (IOException e) {
            throw new RuntimeException("Failed to read Lua script file", e);
        }

        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(luaScript, Long.class);

        return redisTemplate.execute(redisScript, Collections.singletonList(key), incrementBy);
    }


}
  1. 创建一个Controller来触发Lua脚本的执行:

创建一个Controller类,以便从Web应用程序中触发执行Lua脚本的操作:

复制代码
import com.lfsun.demolfsunstudyredislua.service.RedisLuaService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class LuaController {

    @Autowired
    private RedisLuaService redisLuaService;

    @GetMapping("/executeLua")
    public Long executeLuaScript(@RequestParam("key") String key, @RequestParam("incrementBy") long incrementBy) {
        return redisLuaService.executeLuaScript(key, incrementBy);
    }
}
  1. 启动Spring Boot应用程序:

现在,启动Spring Boot应用程序。使用浏览器或API调用来触发执行Lua脚本的操作,例如访问http://localhost:8080/executeLua?key=money&incrementBy=99999我们的money就会蹭蹭蹭的往上涨。

第0次访问,还没有money:

第1次访问,money 多了99999:

第n次访问,千万富翁:

debug_key、debug_incrementBy为debug调试用的,实际使用中删除。

相关推荐
杨杨杨大侠1 小时前
都能接模型、RAG 和 MCP,Java Agent 框架到底差在哪?
java
Thinker QAQ2 小时前
并发编程(九):BlockingQueue 与 Channel——语言层的原子性、可见性与有序性
java·python·go·并发编程·channel·blockingqueue·message passing
Knight_AL3 小时前
本地服务连接 SaaS 测试环境实践:Docker 部署 Redis 与 RocketMQ 完成接口联调
redis·docker·rocketmq
霸道流氓气质4 小时前
RAG 可观测性与生产监控实战:四层遥测模型、五大仪表盘与 OpenTelemetry 全链路追踪的 Java 生产级实现
java·人工智能·python
AOI小白新手上路4 小时前
autodl常用的tar 打包下载(数据集)命令手册:逐段拆解与套用模板
java·大数据·数据库
夕除4 小时前
redis--服务器优化
redis
xiaoqiMikko5 小时前
Redis 实战(一):内存满了 —— 拒写、淘汰、被系统杀掉,以及删了 key 内存为什么不降(6.2.4 实测)
redis·后端
dishugj6 小时前
系统架构风险点、敏感点和权衡点的概念和区分
java·开发语言
苜蓿muxu6 小时前
常用代码命名规范
java