此版本仍在开发中,尚未被视为稳定版本。如需最新的稳定版本,请使用 Spring Data Redis 3.4.0spring-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 脚本运行常见的 “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, singletonList("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, singletonList("key"), asList(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