Annotated Endpoint Method Signature
到目前为止,我们已经向端点中注入了一个简单的 String
,但它实际上可以具有一个非常灵活的方法签名。以下示例对其进行了重新编写,以使用自定义头注入 Order
:
So far, we have been injecting a simple String
in our endpoint, but it can actually have a very flexible method signature.
The following example rewrites it to inject the Order
with a custom header:
@Component
public class MyService {
@RabbitListener(queues = "myQueue")
public void processOrder(Order order, @Header("order_type") String orderType) {
...
}
}
以下列表显示了可与侦听器端点中的参数匹配的参数:
The following list shows the arguments that are available to be matched with parameters in listener endpoints:
-
The raw
org.springframework.amqp.core.Message
. -
The
MessageProperties
from the rawMessage
. -
The
com.rabbitmq.client.Channel
on which the message was received. -
The
org.springframework.messaging.Message
converted from the incoming AMQP message. -
@Header
-annotated method arguments to extract a specific header value, including standard AMQP headers. -
@Headers
-annotated argument that must also be assignable tojava.util.Map
for getting access to all headers. -
The converted payload
未带注解且不是受支持类型之一(即 Message
、MessageProperties
、Message<?>
和 Channel
)的元素与有效负载匹配。你可以通过使用 @Payload
为参数添加注解,使其显式。你还可以通过添加额外的 @Valid
开启验证。
A non-annotated element that is not one of the supported types (that is,
Message
, MessageProperties
, Message<?>
and Channel
) is matched with the payload.
You can make that explicit by annotating the parameter with @Payload
.
You can also turn on validation by adding an extra @Valid
.
注入 Spring 的消息抽象的功能非常有用,可以从 transport 特定的消息中存储的所有信息中受益,而无需依赖 transport 特定的 API。以下示例显示如何实现:
The ability to inject Spring’s message abstraction is particularly useful to benefit from all the information stored in the transport-specific message without relying on the transport-specific API. The following example shows how to do so:
@RabbitListener(queues = "myQueue")
public void processOrder(Message<Order> order) { ...
}
方法参数的处理由 DefaultMessageHandlerMethodFactory
提供,你可以进一步对其进行自定义以支持其他方法参数。转换和验证支持也可以在那里进行自定义。
Handling of method arguments is provided by DefaultMessageHandlerMethodFactory
, which you can further customize to support additional method arguments.
The conversion and validation support can be customized there as well.
例如,如果我们希望在处理之前确保我们的 Order 有效,我们可以用 @Valid
为有效负载添加注解,并配置必要的验证器,如下所示:
For instance, if we want to make sure our Order
is valid before processing it, we can annotate the payload with @Valid
and configure the necessary validator, as follows:
@Configuration
@EnableRabbit
public class AppConfig implements RabbitListenerConfigurer {
@Override
public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
registrar.setMessageHandlerMethodFactory(myHandlerMethodFactory());
}
@Bean
public DefaultMessageHandlerMethodFactory myHandlerMethodFactory() {
DefaultMessageHandlerMethodFactory factory = new DefaultMessageHandlerMethodFactory();
factory.setValidator(myValidator());
return factory;
}
}