首页 > 解决方案 > Redis 管道使用

问题描述

我试图了解管道是如何工作的,并且想尝试不同的东西。我注意到如果密钥没有过期密钥,则没有设置过期密钥的方法,所以我用 Jedis 做了一个例子。

例子

Map<String, Response> responses = new HashMap<>();

long start = System.currentTimeMillis();
try (Jedis resource = redisManager.getResource()) {

    Pipeline pipeline = resource.pipelined();

    responses.put("time", pipeline.ttl(args[1]));

    pipeline.sync();

    pipeline.multi();

    if (responses.get("time").get().equals(-1L)) {
        pipeline.expire(args[1], 15);
    }

    pipeline.exec();

}

我想知道我应该这样使用还是您对此有任何想法?我找不到任何解决方案。

标签: javaredispipelinejedisttl

解决方案


如果您在将每个命令发送到管道后同步并获得结果,那么在没有流水线的情况下发送命令并没有太大区别。流水线的好处来自于发送许多命令而不等待它们的响应,然后一次读取所有响应(从而消除了等待响应所花费的大量时间。更多信息:https://redis。 io/主题/流水线)。

所以你上面的一个更“管道-y”的实现看起来像这样(请原谅任何错误的管道方法名称,我主要使用 Spring Data 而不是直接的 Jedis):

List<String> keysToCheckForTtl = ...
Map<String, Response> responses = new HashMap<>();

for (String key : keysToCheckForTtl) {
  responses.put(key, pipeline.ttl(key));
}

pipeline.sync(); // get the responses back for all TTL commands

for (String key : keysToCheckForTtl) {
  if (responses.get(key).get().equals(-1L)) {
        pipeline.expire(key, 15);
  }
}

pipeline.exec(); // finalize all expire commands

如您所见,这适用于要检查和过期的密钥列表。如果您只需要检查然后使单个密钥过期,则不需要管道。


推荐阅读