执行脚本

Wu Jun 2020-01-04 18:43:49
Categories: > Tags:

1 配置

@Configuration
@EnableTransactionManagement
public class RedisTemplateConfig {

    @Bean("redisTemplate")
    public RedisTemplate redisTemplate(RedisConnectionFactory redisConnectionFactory) {
        StringRedisTemplate template = new StringRedisTemplate();
        template.setConnectionFactory(redisConnectionFactory);
        template.setDefaultSerializer(new GenericJackson2JsonRedisSerializer());
        template.setKeySerializer(new StringRedisSerializer());
        template.setValueSerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashKeySerializer(new GenericJackson2JsonRedisSerializer());
        template.setHashValueSerializer(new GenericJackson2JsonRedisSerializer());
        return template;
    }


    @Bean("setNxEx")
    public RedisScript<Boolean> setNxPx(){
        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("scripts/setNxEx.lua")));
        redisScript.setResultType(Boolean.class);
        return redisScript;
    }

    @Bean("delLock")
    public RedisScript<Boolean> delLock(){
        DefaultRedisScript<Boolean> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("scripts/delLock.lua")));
        redisScript.setResultType(Boolean.class);
        return redisScript;
    }
    
    @Bean("setIfLarger")
    public RedisScript<Long> setIfLarger(){
        DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>();
        redisScript.setScriptSource(new ResourceScriptSource(new ClassPathResource("scripts/setIfLarger.lua")));
        redisScript.setResultType(Long.class);
        return redisScript;
    }
}

2 脚本

delLock.lua

if redis.call("get",KEYS[1]) == ARGV[1] then
    return redis.call("del",KEYS[1])
else
    return 0
end

setNxEx.lua

return redis.call('SET', KEYS[1], ARGV[1], 'NX', 'EX', ARGV[2])

setIfLarger.lua

local current = redis.call("get",KEYS[1])
if(not current or current < ARGV[1])
then
    redis.call("set",KEYS[1],ARGV[1])
    return ARGV[1]+0
else
    return current+0
end

3 使用

@Autowired
@Qualifier("setIfLarger")
private RedisScript<String> setIfLargerScript;
    

String key;
Long value;
String timeMark = redisTemplate.execute(setIfLargerScript, Arrays.asList(key), value);