自动将 JSON 字节从 RabbitMQ 队列转换为对象

Automatically converting JSON bytes from RabbitMQ queue to object

是否可以配置 Spring AMQP 以便自动将队列中的消息(本质上是 JSON 字符串)转换为所需类型的对象?

到目前为止我尝试过的:

1) 我的配置文件:

<rabbit:listener-container connection-factory="rabbitConnectionFactory" message-converter="jsonMessageConverter">
   <rabbit:listener ref="foo" method="listen" queue-names="test_queue"/>
</rabbit:listener-container>
<bean id="foo" class="foo.FooListener"/>
<bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.JsonMessageConverter"/>

2) 我的监听器 FooListener 有方法 listen(FooMessage foo) { ... }

3) 我的 FooMessage 只是简单的 POJO,我的 test_queue 中的消息只是 JSON 格式的 FooMessage 的序列化实例。

所以它不起作用,Spring 声明 listen(byte[] msg) 方法:

java.lang.NoSuchMethodException: foo.FooListener.listen([B).

可以吗?

请为 Jackson2JsonMessageConverter 阅读 documentation。 并注意备注:

In versions prior to 1.6, if type information is not present, conversion would fail. Starting with version 1.6, if type information is missing, the converter will convert the JSON using Jackson defaults (usually a map).

因此,与 POJO 处理程序的目标参数类型无关,MessageProperties 必须包含 __TypeId__ 信息。

为满足您的要求,请考虑改用 @RabbitListener

请参阅 Spring AMQP 1.6 中的新闻同一部分。

虽然可以随意提出一个 JIRA issue,但我们可能会考虑一些通用 MessageListenerAdapter 的钩子,我们通过 listener ref="foo" method="listen" 知道该方法,因此可以推断出目标参数类型转换前。

好吧,实际上这个东西在 Spring AMQP 甚至更早的 1.6 版本中都很有效。问题是我的消息 content-type 不正确,只是 text/plain.

如果以适当的方式发送带有 json 的消息,请说

template.convertAndSend("test_queue", "test_queue", new FooMessage("blablabla","blabla"));

正确设置 template:

<rabbit:template id="amqpTemplate"
                     connection-factory="rabbitConnectionFactory"
                     message-converter="jsonMessageConverter"
                     />
<bean id="jsonMessageConverter" class="org.springframework.amqp.support.converter.Jackson2JsonMessageConverter"/>

所以方法 listen(FooMessage foo) { ... } 被从消息自动创建的 FooMessage 类型的对象调用。