Multi-method Listeners
从版本 1.5.0 开始,你可以在类级别指定 @RabbitListener
注解。这与新的 @RabbitHandler
注解一起使单个侦听器调用不同的方法,具体取决于传入消息的有效负载类型。最好使用示例进行描述:
Starting with version 1.5.0, you can specify the @RabbitListener
annotation at the class level.
Together with the new @RabbitHandler
annotation, this lets a single listener invoke different methods, based on
the payload type of the incoming message.
This is best described using an example:
@RabbitListener(id="multi", queues = "someQueue")
@SendTo("my.reply.queue")
public class MultiListenerBean {
@RabbitHandler
public String thing2(Thing2 thing2) {
...
}
@RabbitHandler
public String cat(Cat cat) {
...
}
@RabbitHandler
public String hat(@Header("amqp_receivedRoutingKey") String rk, @Payload Hat hat) {
...
}
@RabbitHandler(isDefault = true)
public String defaultMethod(Object object) {
...
}
}
在这种情况下,如果转换后的有效负载是 Thing2
、Cat
或 Hat
,则会调用 @RabbitHandler
方法。您应该明白,系统必须能够根据有效负载类型识别唯一的方法。对类型进行检查,以检验是否可分配给没有注释的单个参数,或者是否注释了 @Payload
注释。请注意,与方法级别 @RabbitListener
(described earlier) 中讨论的一样,适用的方法签名是相同的。
In this case, the individual @RabbitHandler
methods are invoked if the converted payload is a Thing2
, a Cat
, or a Hat
.
You should understand that the system must be able to identify a unique method based on the payload type.
The type is checked for assignability to a single parameter that has no annotations or that is annotated with the @Payload
annotation.
Notice that the same method signatures apply, as discussed in the method-level @RabbitListener
(described earlier).
从版本 2.0.3 开始,可以将 @RabbitHandler
方法指定为默认方法,当没有其他方法匹配时,它就会被调用。最多只能指定一个方法。
Starting with version 2.0.3, a @RabbitHandler
method can be designated as the default method, which is invoked if there is no match on other methods.
At most, one method can be so designated.
@RabbitHandler
仅用于在转换后处理消息有效负载,如果你希望接收未转换的原始 Message
对象,则必须对方法使用 @RabbitListener
,而不是类。
@RabbitHandler
is intended only for processing message payloads after conversion, if you wish to receive the unconverted raw Message
object, you must use @RabbitListener
on the method, not the class.