java - 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();
}
我想知道我应该这样使用还是您对此有任何想法?我找不到任何解决方案。
解决方案
如果您在将每个命令发送到管道后同步并获得结果,那么在没有流水线的情况下发送命令并没有太大区别。流水线的好处来自于发送许多命令而不等待它们的响应,然后一次读取所有响应(从而消除了等待响应所花费的大量时间。更多信息: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
如您所见,这适用于要检查和过期的密钥列表。如果您只需要检查然后使单个密钥过期,则不需要管道。
推荐阅读
- windows - 如何在 Windows slave 上的 Jenkinsfile.groovy 中复制具有特定扩展名的文件
- c# - 任务在 Linux 上的 Rider 中找不到“AxImp.exe”
- sql - 无效标识符:sql中多列的总和
- r - 在 R 的另一列中保留不唯一但具有不同标签的行
- javascript - 是什么导致无法在纯 JavaScript 中检测到滚动到 HTML 元素的底部?
- python - 将两个文件动态导入python中的另一个文件,这两个文件位于不同的目录中
- r - 如何修改嵌套在列表中的数据框而不重新分配
- c - 行 *x=y 是否等于 c 中的行 x[0]=y
- c# - 我在 Visual Studio 中遇到 emguCV 问题
- python - For 循环中的元组 - Python