Pipelining

Redis 提供了对 pipelining 的支持,其中涉及向服务器发送多个命令而不等待回复,然后在单步中读取回复。当您需要连续发送多个命令时(例如将许多元素添加到同一个列表中),管道处理可以提高性能。

Redis provides support for pipelining, which involves sending multiple commands to the server without waiting for the replies and then reading the replies in a single step. Pipelining can improve performance when you need to send several commands in a row, such as adding many elements to the same List.

Spring Data Redis 为在管道中运行命令提供了几个`RedisTemplate`方法。如果你不关心管道操作的结果,你可以使用标准的`execute`方法,为`pipeline`参数传递`true`。executePipelined`方法在管道中运行提供的`RedisCallback`或`SessionCallback,并返回结果,如下例所示:

Spring Data Redis provides several RedisTemplate methods for running commands in a pipeline. If you do not care about the results of the pipelined operations, you can use the standard execute method, passing true for the pipeline argument. The executePipelined methods run the provided RedisCallback or SessionCallback in a pipeline and return the results, as shown in the following example:

//pop a specified number of items from a queue
List<Object> results = stringRedisTemplate.executePipelined(
  new RedisCallback<Object>() {
    public Object doInRedis(RedisConnection connection) throws DataAccessException {
      StringRedisConnection stringRedisConn = (StringRedisConnection)connection;
      for(int i=0; i< batchSize; i++) {
        stringRedisConn.rPop("myqueue");
      }
    return null;
  }
});

前面的示例在管道中运行队列中项目的批量右弹出。results `List`包含所有弹出的项目。`RedisTemplate`使用其值、哈希键和哈希值序列化器在返回之前反序列化所有结果,因此前面的示例中返回的项目是字符串。还有其他`executePipelined`方法可以让你为管道结果传递一个自定义序列化器。

The preceding example runs a bulk right pop of items from a queue in a pipeline. The results List contains all of the popped items. RedisTemplate uses its value, hash key, and hash value serializers to deserialize all results before returning, so the returned items in the preceding example are Strings. There are additional executePipelined methods that let you pass a custom serializer for pipelined results.

请注意,从`RedisCallback`返回的值必须为`null`,因为该值将被丢弃,以返回管道命令的结果。

Note that the value returned from the RedisCallback is required to be null, as this value is discarded in favor of returning the results of the pipelined commands.

Lettuce 驱动程序支持细粒度的刷新控制,它允许在命令出现时刷新命令,缓冲或在连接关闭时发送命令。

The Lettuce driver supports fine-grained flush control that allows to either flush commands as they appear, buffer or send them at connection close.

LettuceConnectionFactory factory = // ...
factory.setPipeliningFlushPolicy(PipeliningFlushPolicy.buffered(3)); 1
1 Buffer locally and flush after every 3rd command.