没有MULTI的ERR EXEC-Vertx-Redis 3.7.0

时间:2019-05-16 06:22:24

标签: vert.x

我正在尝试使用multi执行vertx-redis-client,版本为3.7.0。该文档非常糟糕,我什至不知道如何使用multi。我以某种方式尝试了以下代码。输出非常不一致。有时它会正常执行,有时会抛出错误ERR EXEC without MULTI

代码:

        Map<String,String> keyFields =  new HashMap<>();
        keyFields.put("{test}:t1", "f1");
        keyFields.put("{test}:t2", "f2");
        redisAPI.multi(ar1 -> {
            for (Map.Entry<String, String> e: keyFields.entrySet()) {
                redisAPI.hget(e.getKey(), e.getValue(), ar2 -> {
                    if ("QUEUED".equals(ar2.result().toString())) {
                        System.out.println("its queued");
                        redisAPI.exec(execEvent -> { 
                            System.out.println(execEvent);
                            System.out.println("Result is: "+ execEvent.result());
                        });
                    } else {
                        System.out.println("Result is: "+ ar2.result());
                    }
                });
            }
        });

输出错误:

its queued
Future{cause=ERR EXEC without MULTI}
Result is: null
its queued
Future{cause=ERR EXEC without MULTI}
Result is: null

没有错误:

Result is: v2
Result is: v1

代码有什么问题?

1 个答案:

答案 0 :(得分:0)

此代码有一个小错误。让我们用redis命令来看看它发生了什么:

MULTI // Line 4
HGET "{test}:t1", "f1" // Line 6 (inside loop)
EXEC // Line 9 (because the response is immediate the callback gets called here)
HGET "{test}:t2", "f2" // Line 6 (second iteration of the loop)
EXEC // Line 9 Fail since there's no multi

即使事情有点延迟,也会出现错误:

MULTI // Line 4
HGET "{test}:t1", "f1" // Line 6 (inside loop)
HGET "{test}:t2", "f2" // Line 6 (second iteration of the loop)
EXEC // Line 9
EXEC // Line 9 Fail since there's no multi

最后,预期结果与测试不匹配,因为您在未填充初始哈希值的情况下调用了HGET(也许为了简化示例而省略了此值)。

我建议使用其他方法:

redis.batch(Arrays.asList(
  cmd(MULTI),
  cmd(HGET).arg("{test}:t1").arg("f1"),
  cmd(HGET).arg("{test}:t2").arg("f2");
  cmd(EXEC)
), batch -> {
  // At this moment you have all responses
});

这种方法可避免您遇到异步循环。确实并未对此进行记录。