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

相关推荐
Java陈序员1 分钟前
数据同步神器!一款搞定多种数据源同步的开源中间件!
java·spring boot·mysql
大G的笔记本5 分钟前
redis相关概念解释
redis
liuhaikang15 分钟前
鸿蒙高性能动画库——lottie-turbo
java·开发语言·nginx
面对疾风叭!哈撒给19 分钟前
Liunx之Docker 安装启动 influxdb2
java·spring cloud·docker
沛沛老爹21 分钟前
Web开发者快速上手AI Agent:基于Function Calling的提示词应用优化实战
java·人工智能·llm·agent·web·企业开发·function
麦兜*24 分钟前
Spring Boot 启动过程全解析:从main方法到Tomcat启动的魔法之旅
java·spring boot·后端·spring·tomcat·firefox
零度@32 分钟前
Java-Redis 缓存「从入门到黑科技」2026 版
java·redis·缓存
zzhongcy32 分钟前
多级缓存对比(Caffeine + Redis),以及缓存不一致问题的解决
java
optimistic_chen34 分钟前
【Redis 系列】常用数据结构---ZSET类型
数据结构·数据库·redis·xshell·zset·redis命令
带刺的坐椅34 分钟前
灵动如画 —— 初识 Solon Graph Fluent API 编排
java·ai·agent·solon·flow·langgraph