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

相关推荐
小咕聊编程16 分钟前
【含文档+PPT+源码】基于spring boot的固定资产管理系统
java·spring boot·后端
roykingw17 分钟前
【终极面试集锦】如何设计微服务熔断体系?
java·微服务·面试
我命由我1234518 分钟前
Spring Cloud - Spring Cloud 微服务概述 (微服务的产生与特点、微服务的优缺点、微服务设计原则、微服务架构的核心组件)
java·运维·spring·spring cloud·微服务·架构·java-ee
それども21 分钟前
忽略Lombok构建警告
java·开发语言·jvm
用户685453759776928 分钟前
🎮 Java设计模式:从青铜到王者的代码修炼手册
java·后端
马尚道42 分钟前
Java高手速成--吃透源码+手写组件+定制开发教程
java
我命由我123451 小时前
Spring Cloud - Spring Cloud 注册中心与服务提供者(Spring Cloud Eureka 概述、微服务快速入门、微服务应用实例)
java·spring boot·spring·spring cloud·微服务·eureka·java-ee
MetaverseMan1 小时前
Java Spring 框架的`@Autowired` 注解 以及依赖注入分析
java·开发语言·spring
一吃就胖的1 小时前
【给服务器安装服务器安装nacos】
java·运维·服务器
christine-rr1 小时前
linux常用命令——其他
linux·服务器·网络·数据库·redis·ubuntu