【Spring连载】使用Spring Data访问Redis(十)----Lua脚本支持Scripting

【Spring连载】使用Spring Data访问Redis(十)----Lua脚本支持Scripting

Redis 2.6及更高版本支持通过eval 和 evalsha 命令运行Lua脚本。Spring Data Redis为运行处理序列化的脚本提供了高级抽象,并自动使用Redis脚本缓存。
脚本可以通过调用RedisTemplate和ReactiveRedisTemplate的execute方法来运行。两者都使用可配置的ScriptExecutor(或ReactiveScriptExecutor)来运行所提供的脚本。默认情况下,ScriptExecutor(或ReactiveScriptExecutor)负责序列化提供的键和参数,并反序列化脚本结果。这是通过template的键和值序列化程序完成的。还有一个额外的重载,允许你为脚本参数和结果传递自定义序列化程序。
默认的ScriptExecutor通过检索脚本的SHA1并尝试首先运行evalsha来优化性能,如果Redis脚本缓存中还没有脚本,则返回eval。
以下示例使用Lua脚本运行一个常见的"check-and-set"场景。这是Redis脚本的理想用例,因为它要求以原子方式(atomically)运行一组命令,并且一个命令的行为会受到另一个命令结果的影响。

java 复制代码
@Bean
public RedisScript<Boolean> script() {

  ScriptSource scriptSource = new ResourceScriptSource(new ClassPathResource("META-INF/scripts/checkandset.lua"));
  return RedisScript.of(scriptSource, Boolean.class);
}
java 复制代码
public class Example {

  @Autowired
  RedisOperations<String, String> redisOperations;

  @Autowired
  RedisScript<Boolean> script;

  public boolean checkAndSet(String expectedValue, String newValue) {
    return redisOperations.execute(script, singletonList("key"), asList(expectedValue, newValue));
  }
}
lua 复制代码
-- checkandset.lua
local current = redis.call('GET', KEYS[1])
if current == ARGV[1]
  then redis.call('SET', KEYS[1], ARGV[2])
  return true
end
return false

前面的代码配置了一个RedisScript,指向一个名为checkandset.lua的文件,该文件应该返回一个布尔值。脚本resultType应为Long, Boolean, List或反序列化的值类型之一。如果脚本返回丢弃(throw-away)状态(特别是OK),它也可以为null。

最好在应用程序上下文中配置DefaultRedisScript的单个实例,以避免在每次运行脚本时重新计算脚本的SHA1。

然后,上面的checkAndSet方法运行脚本。脚本可以作为事务或管道的一部分在SessionCallback中运行。有关更多信息,请参阅"Redis事务"和"Redis管道 pipeline"。

Spring Data Redis提供的脚本支持还允许您使用Spring Task和Scheduler抽象来安排Redis脚本定期运行。有关更多详细信息,请参阅Spring Framework文档。

相关推荐
笨手笨脚の1 小时前
Spring Core常见错误及解决方案
java·后端·spring
奶油松果1 小时前
Springboot自动装配 - redis和redission
java·spring boot·redis
siriuuus2 小时前
Redis 安装、多实例部署、主从复制及 Cluster 实践
数据库·redis·centos
YDS8295 小时前
MyBatis-Plus精讲 —— 从快速入门到项目实战
java·后端·spring·mybatis·mybatis-plus
吃喝不愁霸王餐APP开发者5 小时前
霸王餐API文档自动化:Spring REST Docs与Asciidoctor多模块聚合
数据库·spring·自动化
小马爱打代码5 小时前
Spring AI:文生图:调用通义万相 AI 大模型
java·人工智能·spring
清晓粼溪6 小时前
SpringMVC02:扩展知识
java·后端·spring
谷哥的小弟6 小时前
Spring Framework源码解析——Ordere
java·后端·spring·源码
摇滚侠7 小时前
2025最新 SpringCloud 教程,Seata-原理-二阶提交协议,笔记70
笔记·spring·spring cloud
清晓粼溪8 小时前
SpringMVC-01:基础知识
java·spring