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.propertiesapplication.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调试用的,实际使用中删除。

相关推荐
陈大爷(有低保)18 分钟前
UDP Socket聊天室(Java)
java·网络协议·udp
kinlon.liu31 分钟前
零信任安全架构--持续验证
java·安全·安全架构·mfa·持续验证
码爸1 小时前
flink 批量压缩redis集群 sink
大数据·redis·flink
王哲晓1 小时前
Linux通过yum安装Docker
java·linux·docker
java6666688881 小时前
如何在Java中实现高效的对象映射:Dozer与MapStruct的比较与优化
java·开发语言
Violet永存1 小时前
源码分析:LinkedList
java·开发语言
执键行天涯1 小时前
【经验帖】JAVA中同方法,两次调用Mybatis,一次更新,一次查询,同一事务,第一次修改对第二次的可见性如何
java·数据库·mybatis
Jarlen1 小时前
将本地离线Jar包上传到Maven远程私库上,供项目编译使用
java·maven·jar
蓑 羽1 小时前
力扣438 找到字符串中所有字母异位词 Java版本
java·算法·leetcode
Reese_Cool1 小时前
【C语言二级考试】循环结构设计
android·java·c语言·开发语言