此版本仍在开发中,尚未被视为稳定版本。如需使用最新稳定版本,请访问 Spring Data Redis 4.0.4spring-doc.cadn.net.cn

脚本

Redis 2.6 及更高版本通过 evalevalsha 命令提供了运行 Lua 脚本的支持。Spring Data Redis 提供了运行脚本的高级抽象,可处理序列化并自动使用 Redis 脚本缓存。spring-doc.cadn.net.cn

脚本可以通过调用 executeRedisTemplateReactiveRedisTemplate 方法来运行。两者都使用可配置的 ScriptExecutor(或 ReactiveScriptExecutor)来执行提供的脚本。默认情况下,ScriptExecutor(或 ReactiveScriptExecutor)负责序列化提供的键和参数,并反序列化脚本结果。这是通过模板的键和值序列化器完成的。还有一个额外的重载方法,允许您为脚本参数和结果传递自定义序列化器。spring-doc.cadn.net.cn

默认的 ScriptExecutor 通过获取脚本的 SHA1 哈希值来优化性能,并首先尝试运行 evalsha;如果脚本尚未存在于 Redis 脚本缓存中,则回退到 evalspring-doc.cadn.net.cn

以下示例通过使用 Lua 脚本执行一个常见的“检查并设置”(check-and-set)场景。这是 Redis 脚本的理想用例,因为它要求一组命令以原子方式执行,并且其中一个命令的行为会受到另一个命令结果的影响。spring-doc.cadn.net.cn

@Bean
public RedisScript<Boolean> script() {

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

  @Autowired
  RedisOperations<String, String> redisOperations;

  @Autowired
  RedisScript<Boolean> script;

  public boolean checkAndSet(String expectedValue, String newValue) {
    return redisOperations.execute(script, List.of("key"), expectedValue, newValue);
  }
}
public class Example {

  @Autowired
  ReactiveRedisOperations<String, String> redisOperations;

  @Autowired
  RedisScript<Boolean> script;

  public Flux<Boolean> checkAndSet(String expectedValue, String newValue) {
    return redisOperations.execute(script, List.of("key"), expectedValue, newValue);
  }
}
-- 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

上述代码配置了一个指向名为 checkandset.lua 的文件的 RedisScript,该文件预期返回一个布尔值。脚本 resultType 应为 LongBooleanList 之一,或为反序列化的值类型。如果脚本返回一个临时状态(具体为 OK),则也可以是 nullspring-doc.cadn.net.cn

在应用程序上下文中配置一个 DefaultRedisScript 的单例实例是理想的做法,以避免每次执行脚本时都重新计算脚本的 SHA1。

上述 checkAndSet 方法随后运行脚本。脚本可以在 SessionCallback 内作为事务或管道的一部分运行。有关更多信息,请参阅“Redis 事务”和“管道化”。spring-doc.cadn.net.cn

Spring Data Redis 提供的脚本支持还允许你利用 Spring 的任务(Task)和调度器(Scheduler)抽象,定期执行 Redis 脚本。更多详细信息,请参阅Spring Framework文档。spring-doc.cadn.net.cn