Using Container Factories

引入了侦听器容器工厂,以支持 `@RabbitListener`并使用 `RabbitListenerEndpointRegistry`注册容器,如 Programmatic Endpoint Registration中所述。

Listener container factories were introduced to support the @RabbitListener and registering containers with the RabbitListenerEndpointRegistry, as discussed in Programmatic Endpoint Registration.

从版本 2.1 开始,它们可以用于创建任何侦听器容器,甚至是无侦听器的容器(例如,用于 Spring Integration 中)。当然,在启动容器之前必须添加一个侦听器。

Starting with version 2.1, they can be used to create any listener container — even a container without a listener (such as for use in Spring Integration). Of course, a listener must be added before the container is started.

创建这种容器有两种方法:

There are two ways to create such containers:

  • Use a SimpleRabbitListenerEndpoint

  • Add the listener after creation

以下示例显示如何使用 SimpleRabbitListenerEndpoint 创建侦听器容器:

The following example shows how to use a SimpleRabbitListenerEndpoint to create a listener container:

@Bean
public SimpleMessageListenerContainer factoryCreatedContainerSimpleListener(
        SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory) {
    SimpleRabbitListenerEndpoint endpoint = new SimpleRabbitListenerEndpoint();
    endpoint.setQueueNames("queue.1");
    endpoint.setMessageListener(message -> {
        ...
    });
    return rabbitListenerContainerFactory.createListenerContainer(endpoint);
}

以下示例显示如何在创建后添加侦听器:

The following example shows how to add the listener after creation:

@Bean
public SimpleMessageListenerContainer factoryCreatedContainerNoListener(
        SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory) {
    SimpleMessageListenerContainer container = rabbitListenerContainerFactory.createListenerContainer();
    container.setMessageListener(message -> {
        ...
    });
    container.setQueueNames("test.no.listener.yet");
    return container;
}

在任一情况下,侦听器也可以是 ChannelAwareMessageListener,因为它现在是 MessageListener 的一个子接口。

In either case, the listener can also be a ChannelAwareMessageListener, since it is now a sub-interface of MessageListener.

如果你希望创建具有相似属性的多个容器,或使用 Spring Boot 自动配置提供的预配置容器工厂(或同时使用两者),这些技术会很有用。

These techniques are useful if you wish to create several containers with similar properties or use a pre-configured container factory such as the one provided by Spring Boot auto configuration or both.

通过这种方式创建的容器是常规 @Bean 实例,且并未在 RabbitListenerEndpointRegistry 中注册。

Containers created this way are normal @Bean instances and are not registered in the RabbitListenerEndpointRegistry.