此版本仍在开发中,尚不被认为是稳定的。对于最新的稳定版本,请使用 Spring Data Redis 3.5.3spring-doc.cadn.net.cn

脚本

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

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

默认值ScriptExecutor通过检索脚本的 SHA1 并首先尝试运行来优化性能evalsha,回退到eval如果脚本尚未存在于 Redis 脚本缓存中。spring-doc.cadn.net.cn

以下示例使用 Lua 脚本运行常见的“检查和设置”场景。这是 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

前面的代码配置了一个RedisScript指向名为checkandset.lua,预计返回布尔值。脚本resultType应该是其中之一Long,Boolean,List或反序列化值类型。也可以是null如果脚本返回 throw-away 状态(具体来说,OK).spring-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