当使用RedisTemplate执行lua脚本时,结果令人困惑。

问题描述 投票:2回答:1

我正在使用spring-boot-starter-data-redis 2.0.5.RELEASE。我用RestTemplate执行一个lua脚本。脚本的内容是

-- hold.lua
if redis.call('get', KEYS[1]) == ARGV[1] then
    redis.call('pexpire', KEYS[1], ARGV[2])
    return 1
end
return 0

Java代码。

@Override
public void executeHold(String lockKey, String lockValue, long expireInMillis) {
    DefaultRedisScript<Boolean> holdScript = new DefaultRedisScript<>();
    holdScript.setLocation(new ClassPathResource("lua/hold.lua"));
    holdScript.setResultType(Boolean.class);
    // CODE 1
    Boolean result = redisTemplate.execute(holdScript, Collections.singletonList(lockKey), lockValue, expireInMillis);
    // END of CODE 1
    //        // CODE 2
    //        String script = holdScript.getScriptAsString();
    //        Boolean result = redisTemplate.execute(new RedisCallback<Boolean>() {
    //            @Override
    //            public Boolean doInRedis(RedisConnection connection) throws DataAccessException {
    //                return connection.scriptingCommands()
    //                        .eval(
    //                                script.getBytes(),
    //                                ReturnType.fromJavaType(Boolean.class),
    //                                1,
    //                                lockKey.getBytes(),
    //                                lockValue.getBytes(),
    //                                String.valueOf(expireInMillis).getBytes()
    //                        );
    //            }
    //        });
    //        // END of CODE 2
    System.out.println(holdScript.getSha1());
    LOGGER.debug("Execute holdScript, result={}, content=\n{}", result, holdScript.getScriptAsString());
}

我已经设置了 lockKey 在redis中。

127.0.0.1:6379> set lockKey lockValue PX 600000 NX

当我运行上面的代码时 CODE 1 二手的,我总是得到 result = false.

但当我修改上面的代码,用 CODE 2 使用,我可以得到正确的结果预期。

这真的让我很困惑,谁能帮我找到它的问题所在?谢谢你。

我想做的是 .

java spring-boot lua redis spring-data-redis
1个回答
0
投票

我也遇到了类似的问题。问题的根本原因是我在redis模板中使用了json序列化器,它在我传递给脚本的字符串值中添加了额外的引号。将序列化器改为字符串序列化器后,我的问题得到了解决。

© www.soinside.com 2019 - 2024. All rights reserved.