StreamOperations类的read()方法
read
@Nullable
List<MapRecord<K,HK,HV>> read(Consumer consumer, StreamReadOptions readOptions, StreamOffset
使用消费者组从一个或多个 StreamOffset 中读取记录。
Read records from one or more StreamOffsets using a consumer group.
Parameters:
- consumer - consumer/group.
- readOptions - read arguments.
- streams - the streams to read from.
Returns:
列出结果流的成员。在管道/事务中使用时为 null。
list with members of the resulting stream. null when used in pipeline / transaction.
See Also:
Redis Documentation: XREADGROUP
https://redis.io/docs/latest/commands/xreadgroup/
XREADGROUP 命令是 XREAD 命令的一个特殊版本,支持消费者组。您可能需要先了解 XREAD 命令才能理解本页内容。
The XREADGROUP command is a special version of the XREAD command with support for consumer groups. Probably you will have to understand the XREAD command before reading this page will makes sense.
此外,如果您是流新手,我们建议您阅读我们的 Redis 流简介。请务必理解简介中消费者组的概念,以便更轻松地理解此命令的工作原理。
Moreover, if you are new to streams, we recommend to read our introduction to Redis Streams. Make sure to understand the concept of consumer group in the introduction so that following how this command works will be simpler.
read方法调用举例
.read(
Consumer.from("g1", "c1"),
StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2)),
StreamOffset.create(queueName, ReadOffset.lastConsumed())
);
这部分代码中调用了 read 方法,下面介绍每个参数的含义:
-
Consumer.from("g1", "c1")
- 这里用
Consumer.from("g1", "c1")创建了一个消费者,"g1"表示消费者所属的消费组的名字。"c1"表示消费者自己的名字。
- Redis Streams 支持消费者组(Consumer Group),即多个消费者可以共同消费同一条消息,每个消费者负责其中的部分数据。通过指定消费组与消费者名称,确保每个消费者处理自己未处理的消息。
- 这里用
-
StreamReadOptions.empty().count(1).block(Duration.ofSeconds(2))
StreamReadOptions用于设置读取选项:.empty()表示使用默认的读取选项基础上进行配置。.count(1)表示一次最多读取 1 条记录。.block(Duration.ofSeconds(2))表示如果当前没有可消费的消息,就阻塞等待 2 秒钟,直到有新消息到达或超时。
- 这种阻塞读取方式非常适合需要等待数据到来时的场景,类似于消息队列中的长轮询模式。
-
StreamOffset.create(queueName, ReadOffset.lastConsumed())
- 这个参数用来指定流的名称以及从什么位置开始读取数据。
queueName是 Redis Stream 的名称。ReadOffset.lastConsumed()表示从上次消费到的位置开始读取,即“已消费”位置之后的消息。
- 在消费者组消费模式下,如果使用
ReadOffset.lastConsumed()就意味着只读取还未被该消费组消费的新消息。
- 这个参数用来指定流的名称以及从什么位置开始读取数据。
- 整体流程
综合以上信息,该代码实现的流程如下:
- 通过
stringRedisTemplate获取一个操作 Stream 的接口。 - 使用消费者组
g1中的消费者c1进行消费。 - 从指定的队列(由变量
queueName表示)中读取最多一条新的消息,并在没有消息时阻塞等待 2 秒钟,防止 CPU 空转。 - 返回的结果是一个
List,其中可能包含一条或零条MapRecord数据(如果在阻塞时间内没有新数据,列表可能为空)。
这种写法常用于实时消息处理场景中,既能够获取最新的数据记录,又可以避免频繁轮询 Redis,从而提高性能和资源利用率。

浙公网安备 33010602011771号