Spring 云流消息 from/to JSON 转换配置
Spring Cloud Stream message from/to JSON conversion configuration
我正在使用 Spring Cloud Stream 和 RabbitMQ 活页夹。它与 byte[]
有效负载和 Java 本机序列化配合使用效果很好,但我需要使用 JSON 有效负载。
这是我的处理器 class。
@EnableBinding(Processor.class)
public class MessageProcessor {
@ServiceActivator(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public OutputDto handleIncomingMessage(InputDto inputDto) {
// Run some job.
return new OutputDto();
}
}
InputDto
和 OutputDto
是带有 Jackson 注释的 POJO。
- 如何配置 JSON 转换策略?
- 消息 headers 应该如何被接受和处理?
在您的消费者中,您可以添加内容类型配置,例如
spring.cloud.stream.bindings.input.content-type: application/x-java-object;type=my.package.InputDto
您还可以添加
spring.cloud.stream.bindings.output.content-type: application/json
强制传出消息负载为 JSON(用于互操作等)。
请注意,"input" 和 "output" 是活页夹通道名称(即在您的应用中 Processor
中定义)。
我认为这很有可能变得更容易或更自动化,但需要一些工程工作才能在 Spring 云中实现这一点。 github 中有一个问题,如果你想关注它:https://github.com/spring-cloud/spring-cloud-stream/issues/156。
要手动将消息发送到 Spring Cloud Stream,您可以自己手动设置 headers(但使用 Stream 更容易)。 JSON 消息在 Rabbit 管理员 UI:
中看起来像这样
priority: 0
delivery_mode: 2
headers:
contentType: text/plain
originalContentType: application/json
content_type: text/plain
我正在使用 Spring Cloud Stream 和 RabbitMQ 活页夹。它与 byte[]
有效负载和 Java 本机序列化配合使用效果很好,但我需要使用 JSON 有效负载。
这是我的处理器 class。
@EnableBinding(Processor.class)
public class MessageProcessor {
@ServiceActivator(inputChannel = Processor.INPUT, outputChannel = Processor.OUTPUT)
public OutputDto handleIncomingMessage(InputDto inputDto) {
// Run some job.
return new OutputDto();
}
}
InputDto
和 OutputDto
是带有 Jackson 注释的 POJO。
- 如何配置 JSON 转换策略?
- 消息 headers 应该如何被接受和处理?
在您的消费者中,您可以添加内容类型配置,例如
spring.cloud.stream.bindings.input.content-type: application/x-java-object;type=my.package.InputDto
您还可以添加
spring.cloud.stream.bindings.output.content-type: application/json
强制传出消息负载为 JSON(用于互操作等)。
请注意,"input" 和 "output" 是活页夹通道名称(即在您的应用中 Processor
中定义)。
我认为这很有可能变得更容易或更自动化,但需要一些工程工作才能在 Spring 云中实现这一点。 github 中有一个问题,如果你想关注它:https://github.com/spring-cloud/spring-cloud-stream/issues/156。
要手动将消息发送到 Spring Cloud Stream,您可以自己手动设置 headers(但使用 Stream 更容易)。 JSON 消息在 Rabbit 管理员 UI:
中看起来像这样priority: 0
delivery_mode: 2
headers:
contentType: text/plain
originalContentType: application/json
content_type: text/plain