读书人

spring-rabbit 中MessageListenerAdap

发布时间: 2012-06-27 14:20:08 作者: rapoo

spring-rabbit 中MessageListenerAdapter类

Message listener adapter adapter that delegates the handling of messages to target listener methods via refection, with flexible message tyep conversion. Allows listener methods to operate on message content types, completely independent from the Rabbit API.

?

By default, the content of incoming Rabbit messges gets extracted before being passed into the target listener method, to let the target method operate on message content tyeps such as String or byte array instead of the raw 'Message'. Message type conversion is delegated to a Spring AMQ 'MessageConverter'. Be default, a 'SimpleMessageConverter' will be used. (If you do not want such automatic message conversijon taking palce, then be sure to set the 'setMessageConverter MessageConverter' to 'null'.)

?

If a target listener method returns a non-null object (typically of a message content type such as String or byte array), it will get wrapped in a Rabbit 'Message' and sent to the exchange of the incoming message with the routingKey that comes from the Rabbit ReplyTo property or via 'setResponseRoutingKey(String) spicified routingKye').

?

Note: The sending of response messges is only available when using the 'ChannelAwareMessageListener' entry point (typically through a Spring message listener container). Usage as 'MessageListener' does 'not' support the generation of response messages.

?

Find below some examples of method signaures compliant with this adapter class. This first example handles all 'Message' types and gets passed the contents of each 'Message' type as an argument. No 'Message' will be sent back as all of these methods return 'void'.

?

?

?

?可以看出XML配置文件不需要我们知道MessageListenerAdapter类,关键点在<rabbit:listener/>Element的method Node上,看注释:

?

Attribute : methodThe name of the listener method to invoke. If not  specified, the target bean is supposed to implement  the MessageListener or ChannelAwareMessageListener  interface.Data Type : string

?如果没有写method,Spring会认为你ref的Bean是一个实现了MessageListener和ChanelAwareMessage接口的类,这两个接口分别有onMessage(Message message)和onMessage(Message message, Channel channel)方法。只有写了method,Spring才会调用MessageListenerAdapter来适配你的POJO类,并默认将method对应的方法变成监听消息的处理方法。默认handleMessage,所以想使用XML配置文件,即使自己写的POJO也是MessageListenerAdapter中默认的适配的handleMessage方法,也是必须在在XML中写上method="handleMessage"。

?

?

?

?

?

?

读书人网 >软件架构设计

热点推荐