springBoot redis分布式锁lua脚本释放异常分析及解决方案
在使用SpringBoot集成redis实现分布式锁时,运用Lua脚本进行锁释放可能会遇到返回值类型不匹配和IllegalStateException异常。本文将通过一个案例分析问题根源并提供解决方案。
问题描述:
开发者使用Lua脚本释放Redis分布式锁,代码片段如下:
public void unlock(String key, Object value) { String script = "if (redis.call('get',KEYS[1]) == ARGV[1]) then return redis.call('del',KEYS[1]) else return 0 end"; DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script); Object result = redisTemplate.execute(redisScript, Collections.singletonList(key), value); }
该脚本旨在检查key的值是否与传入的value匹配,若匹配则删除key(释放锁),否则返回0。运行时出现以下问题:
- 问题一:redisTemplate.execute()返回值类型为Object,而非预期的Long。
- 问题二:单元测试执行unlock方法时抛出org.springframework.data.redis.RedisSystemException: Redis exception; nested exception is io.lettuce.core.RedisException: Java.lang.IllegalStateException异常。
错误原因及解决方案:
分析错误日志和代码,问题主要在于两点:
-
Collections.singletonList(key)类型不匹配:虽然Collections.singletonList(key)返回List
,但redisTemplate在处理keys参数时存在类型转换问题。 Lua脚本期望KEYS为一个键的数组。 使用ArrayList明确指定keys参数类型可以解决此问题。 -
redisTemplate泛型类型不匹配:DefaultRedisScript
期望返回Long类型,但redisTemplate可能无法直接返回Long类型。Lua脚本返回的是数值型字符串,需要进行类型转换。使用StringRedisTemplate更适合处理字符串类型的key和value,并能更直接地处理Lua脚本返回的数值型字符串。
修改后的代码:
StringRedisTemplate stringRedisTemplate; // Inject StringRedisTemplate public void unlock(String key, String value) { // Changed Object value to String value String script = "if (redis.call('GET',KEYS[1]) == ARGV[1]) then return redis.call('DEL',KEYS[1]) else return 0 end"; DefaultRedisScript<Long> redisScript = new DefaultRedisScript<>(script); redisScript.setResultType(Long.class); // Explicitly set the result type List<String> keys = new ArrayList<>(); keys.add(key); Long result = stringRedisTemplate.execute(redisScript, keys, value); // Use StringRedisTemplate System.out.println(result); }
通过以上修改,解决了返回值类型不匹配和IllegalStateException异常,确保Lua脚本正确执行。 关键在于使用StringRedisTemplate并显式设置redisScript的resultType为Long.class。 同时,将value参数的类型改为String,以匹配Lua脚本中的ARGV[1]。
记住在你的spring boot配置中注入StringRedisTemplate。 例如:
@Bean public StringRedisTemplate stringRedisTemplate(RedisConnectionFactory redisConnectionFactory) { StringRedisTemplate template = new StringRedisTemplate(); template.setConnectionFactory(redisConnectionFactory); return template; }