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
配置:
@Bean
public RedisTemplate<String, Object> redisTemplate(RedisConnectionFactory factory) {
RedisTemplate<String, Object> template = new RedisTemplate<>();
template.setConnectionFactory(factory);
template.setKeySerializer(new StringRedisSerializer());
template.setValueSerializer(new StringRedisSerializer());
return template;
}
@Bean
public RedisScript<Boolean> redisScript() { DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>(); ScriptSource scriptSource = new ResourceScriptSource(new ClassPathResource("META-INF/scripts/checkandset.lua")); redisScript.setResultType(Boolean.class); redisScript.setScriptSource(scriptSource); return redisScript;
}
调用:
@Autowired RedisTemplate redisTemplate; @Autowired RedisScript<Boolean> redisScript; List<String> keys = new ArrayList<>(); keys.add("stock"); return redisTemplate.execute(redisScript, keys, 2);