【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文档。

相关推荐
llwszx11 分钟前
Spring中DelayQueue深度解析:从原理到实战(附结构图解析)
java·后端·spring·delayqueue·延迟任务
大春儿的试验田1 小时前
高并发收藏功能设计:Redis异步同步与定时补偿机制详解
java·数据库·redis·学习·缓存
hqxstudying1 小时前
Redis为什么是单线程
java·redis
C182981825752 小时前
OOM电商系统订单缓存泄漏,这是泄漏还是溢出
java·spring·缓存
hello早上好3 小时前
JDK 代理原理
java·spring boot·spring
Fireworkitte3 小时前
Redis 源码 tar 包安装 Redis 哨兵模式(Sentinel)
数据库·redis·sentinel
何苏三月3 小时前
SpringCloud系列 - Sentinel 服务保护(四)
spring·spring cloud·sentinel
纳兰青华3 小时前
bean注入的过程中,Property of ‘java.util.ArrayList‘ type cannot be injected by ‘List‘
java·开发语言·spring·list
魔芋红茶4 小时前
spring-initializer
python·学习·spring
西岭千秋雪_5 小时前
Redis性能优化
数据库·redis·笔记·学习·缓存·性能优化