Programmatic Endpoint Registration

RabbitListenerEndpoint 提供了一个 Rabbit 端点的模型,并负责为此模型配置容器。该基础设施让你可以对端点进行编程配置,除了使用 RabbitListener 注解检测到的端点外。以下示例显示如何实现:

RabbitListenerEndpoint provides a model of a Rabbit endpoint and is responsible for configuring the container for that model. The infrastructure lets you configure endpoints programmatically in addition to the ones that are detected by the RabbitListener annotation. The following example shows how to do so:

@Configuration
@EnableRabbit
public class AppConfig implements RabbitListenerConfigurer {

    @Override
    public void configureRabbitListeners(RabbitListenerEndpointRegistrar registrar) {
        SimpleRabbitListenerEndpoint endpoint = new SimpleRabbitListenerEndpoint();
        endpoint.setQueueNames("anotherQueue");
        endpoint.setMessageListener(message -> {
            // processing
        });
        registrar.registerEndpoint(endpoint);
    }
}

在前面的示例中,我们使用了 SimpleRabbitListenerEndpoint,它提供了要调用的实际 MessageListener,但你也可以构建自己的端点变体来描述自定义调用机制。

In the preceding example, we used SimpleRabbitListenerEndpoint, which provides the actual MessageListener to invoke, but you could just as well build your own endpoint variant to describe a custom invocation mechanism.

请注意,你也可以直接跳过使用 @RabbitListener,并通过 RabbitListenerConfigurer 对端点进行编程注册。

It should be noted that you could just as well skip the use of @RabbitListener altogether and register your endpoints programmatically through RabbitListenerConfigurer.