外发消息转换
Spring AMQP 1.4 引入了 ContentTypeDelegatingMessageConverter
,其中实际的转换器是根据传入的内容类型消息属性选择的。这可以被入站端点使用。
从 Spring Integration 4.3 版本开始,你可以在 outbound 端点使用 ContentTypeDelegatingMessageConverter
,contentType
头信息指定使用哪个转换器。
以下示例配置了一个 ContentTypeDelegatingMessageConverter
,默认转换器是 SimpleMessageConverter
(用于处理 Java 序列化和平面文本),同时还有一个 JSON 转换器:
<amqp:outbound-channel-adapter id="withContentTypeConverter" channel="ctRequestChannel"
exchange-name="someExchange"
routing-key="someKey"
amqp-template="amqpTemplateContentTypeConverter" />
<int:channel id="ctRequestChannel"/>
<rabbit:template id="amqpTemplateContentTypeConverter"
connection-factory="connectionFactory" message-converter="ctConverter" />
<bean id="ctConverter"
class="o.s.amqp.support.converter.ContentTypeDelegatingMessageConverter">
<property name="delegates">
<map>
<entry key="application/json">
<bean class="o.s.amqp.support.converter.Jackson2JsonMessageConverter" />
</entry>
</map>
</property>
</bean>
向 ctRequestChannel
发送消息,并将 contentType
标头设置为 application/json
,这会导致选择 JSON 转换器。
这适用于传出通道适配器和网关。
从 5.0 版本开始,添加到 outbound 消息的 MessageProperties
中的头信息永远不会被映射的头信息覆盖(默认情况下)。以前,只有当消息转换器是 ContentTypeDelegatingMessageConverter
时才会出现这种情况(在这种情况下,头信息会首先被映射,以便选择正确的转换器)。对于其他转换器,如 SimpleMessageConverter
,映射的头信息会覆盖转换器添加的任何头信息。当 outbound 消息中有一些残留的 contentType
头信息(可能是来自 inbound channel adapter)并且正确的 outbound contentType
被错误地覆盖时,这会导致问题。解决方法是在将消息发送到 outbound 终端之前使用头信息过滤器来删除该头信息。
然而,在某些情况下,希望保留以前的行为——例如,当 payload 是包含 JSON 的 String
时,SimpleMessageConverter
并不知道内容并将其 contentType
消息属性设置为 text/plain
,但你的应用程序希望将发送到 outbound 终端的消息的 contentType
头信息覆盖为 application/json
。ObjectToJsonTransformer
默认就是这么做的。
现在,在 outbound channel adapter 和网关(以及 AMQP 支持的通道)上有一个名为 headersMappedLast
的属性。将此属性设置为 true
可以恢复覆盖由转换器添加的属性的行为。
从 5.1.9 版本开始,当我们在生成回复时希望覆盖转换器填充的头信息,为 AmqpInboundGateway
提供了一个类似的 replyHeadersMappedLast
属性。有关更多信息,请参阅其 JavaDocs。