发布(发送消息)
要发布消息,请选择与你应用职责相匹配的抽象级别:
[Reactive]RedisConnection是低层契约,作用于已经序列化好的(byte[])通道和消息数据。[Reactive]RedisOperations(通常通过RedisTemplate)使用模板配置的序列化器进行转换来发布消息。RedisMessageSendingTemplate与 Spring Messaging 集成,将载荷转换委托给一个MessageConverter,根据载荷类型以及(如果存在的话)contentType头来选择转换器。
命令式 API 提供全部三种变体。响应式 API 提供低层连接和 ReactiveRedisOperations 两种变体。
下表总结了各种发送选项之间的差异:
| 变体 | 职责 | 转换模型 |
|---|---|---|
[Reactive]RedisConnection | 发布二进制通道和消息数据。 | 应用代码提供二进制(byte[]/ByteBuffer)值。 |
RedisTemplate / [Reactive]RedisOperations | 通过 Redis 数据访问抽象发布应用值。 | 对消息体使用配置的 value 序列化器。因此发布与模板特定的 value 序列化器绑定。 |
RedisMessageSendingTemplate | 通过 Spring 的 Message<?> 抽象发布,以实现灵活的消息转换。 | 使用 RedisMessageConverters 根据载荷类型以及(如果存在的话)MessageHeaders.CONTENT_TYPE 头选择 MessageConverter。适用于已经使用 Spring Messaging 或注解驱动的监听端点的应用。 |
下例展示了可用的发送变体:
- Imperative
- Reactive
- Spring Messaging
// send message through connection
RedisConnection connection = …
byte[] channel = …
byte[] message = …
connection.pubSubCommands().publish(channel, message);
// send message through RedisOperations
RedisOperations<String, Object> operations = …
Long numberOfClients = operations.convertAndSend("chatroom", "hello!");
// send message through connection
ReactiveRedisConnection connection = …
ByteBuffer channel = …
ByteBuffer message = …
connection.pubSubCommands().publish(channel, message);
// send message through ReactiveRedisOperations
ReactiveRedisOperations<String, String> operations = …
Mono<Long> numberOfClients = operations.convertAndSend("chatroom", "hello!");
RedisMessageSendingTemplate template = …
template.convertAndSend("chatroom", new Greeting("hello", "world"));
template.convertAndSend("chatroom", new Greeting("hello", "world"), 1
Map.of(MessageHeaders.CONTENT_TYPE, "application/json"));
template.convertAndSend("chatroom", new Greeting("hello", "world"), 2
Map.of(MessageHeaders.CONTENT_TYPE, JdkSerializerMessageConverter.APPLICATION_JAVA_SERIALIZED_OBJECT_VALUE));
提供
contentType作为选择转换器的提示。Redis Pub/Sub 不支持请求头,因此它只传输序列化后的消息。为消息体选择 Java 序列化。需要
JdkSerializerMessageConverter才能使用此内容类型。