Jedis pipeline 在调用 sync 方法之前执行命令吗?

huangapple go评论53阅读模式
英文:

Jedis pipeline execute commands before calling sync method?

问题

使用Jedis管道一次性向Redis中添加多个记录。但是在调试代码时,我发现即使在调用 jedis.sync() 方法之前,记录也会出现在Redis中。难道不是预期管道中的所有命令只会在那之后才执行吗?或者可能是将它们批处理成一些固定大小的块吗?

var pipeline = jedis.pipelined();
all.forEach(value -> pipeline.sadd(allPrefix, value));
grouped.forEach((key, value) -> pipeline.hset(groupedPrefix, String.valueOf(key), value));
pipeline.sync();

我这样做对吗?这种行为的原因是什么?

英文:

I am using the Jedis pipeline to add multiple records in Redis at once. But when I am debugging the code I can see the records appear in Redis even before calling jedis.sync() method. Aren't all commands in the pipeline expected to be executed only after that? Or maybe it's just batching them on some chunks with a fixed size?

var pipeline = jedis.pipelined();
all.forEach(value -> pipeline.sadd(allPrefix, value));
grouped.forEach((key, value) -> pipeline.hset(groupedPrefix, String.valueOf(key), value));
pipeline.sync();

Am I doing it the right way and what is the reason for this behavior?

答案1

得分: 3

Jedis pipeline会将命令写入套接字缓冲区。如果所有命令的大小超过了该缓冲区的大小,它将被刷新以腾出空间供更多命令。与此同时,那些已刷新的命令会到达Redis服务器,并且即使没有调用pipeline.sync(),服务器也可能开始处理这些命令。

pipeline.sync()确保所有命令都将被发送到服务器。它确保所有命令会一直保留在缓冲区中,直到调用sync()为止。


如果您希望在触发之前不执行任何命令,考虑使用(任何变体的)事务。事务中的所有命令只在调用exec()后才会执行。

英文:

Jedis pipeline writes the commands in the socket buffer. If the size of all commands exceeds the size of that buffer, it is flushed to make space for more commands. In the mean time, those flushed commands reach to Redis server and the server may start processing those commands; even though pipeline.sync() is not called.

pipeline.sync() ensures that all commands would be sent to server. It does not ensure all commands would be kept in buffer until sync() is called.


If you want something where none of your commands would be executed before a trigger, consider (any variant of) Transaction. All the commands in a transaction gets executed only after exec() is called.

huangapple
  • 本文由 发表于 2023年2月8日 19:00:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/75384816.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定