|
This version is still in development and is not considered stable yet. For the latest stable version, please use Spring Data Redis 4.0.5! |
Publishing (Sending a Message)
To publish a message, choose the abstraction level that matches your application’s responsibility:
-
[Reactive]RedisConnectionis the low-level contract and operates on already-serialized (byte[]) channel and message data. -
[Reactive]RedisOperations(typically throughRedisTemplate) publishes messages by using the template’s configured serializers for conversion. -
RedisMessageSendingTemplateintegrates with Spring Messaging and delegates payload conversion to aMessageConverter, selecting converters according to the payload type and, if present, thecontentTypeheader.
The imperative API offers all three variants.
The reactive API offers the low-level connection and ReactiveRedisOperations variants.
The following table summarizes the differences between the sending options:
| Variant | Responsibility | Conversion model |
|---|---|---|
|
Publish binary channel and message data. |
Application code provides the binary ( |
|
Publish application values through the Redis data access abstraction. |
Uses the configured value serializer for the message body. Publication is therefore bound to the template-specific value serializer. |
|
Publish through Spring’s |
Uses |
The following example shows the available sending variants:
-
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));
| 1 | Provide a contentType as hint for converter selection.
Redis Pub/Sub does not support headers so it transmits only the serialized message. |
| 2 | Select Java Serialization for the message body.
Requires JdkSerializerMessageConverter to use this content type. |