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

相关推荐
古法安卓4 小时前
Android-重启流程源码解析
android·java·android studio
清水白石0085 小时前
Python 类型设计深度解析:TypedDict 能否替代 dataclass?从 JSON 数据边界到 API 设计的最佳实践
java·python·json
晊晌_h5 小时前
嵌入式从0到精通——线程
java·开发语言·jvm
一木 之林5 小时前
五、C++ 新特性、关键字与编译原理(进阶)(二)
java·开发语言·c++
洋不写bug5 小时前
绕过权限检查,访问修改私有属性,反射,枚举,lambda
java·枚举·lambda·反射
evans在进步5 小时前
Java 常用设计模式入门:建造者、工厂、单例、外观与代理
java·python·设计模式
lisin-lee-cooper5 小时前
【leetcode658】有序数组找出k个最接近x的数
java·数据结构·算法
sunburn-6 小时前
Java堆(Heap)详解与实战教学
java·开发语言·数据结构·ide·算法
Kyrie_kk6 小时前
Java--TimeUnit时间单位枚举类(时间单位规范)
java·后端
念何架构之路6 小时前
beego总体架构与工程结构
java·架构·beego