# 32.2.3 接收消息

当Rabbit设施出现时，所有bean都可以注解`@RabbitListener`来创建一个监听器端点。如果没有定义`RabbitListenerContainerFactory`，Spring Boot将自动配置一个默认的`SimpleRabbitListenerContainerFactory`。你可以使用`spring.rabbitmq.listener.type`属性，转换到一个直接的容器。如果定义`MessageConverter` 或者`MessageRecoverer` bean，它将自动关联到默认的factory。

下面的组件创建一个`someQueue`队列上的监听器端点：

```java
@Component
public class MyBean {

    @RabbitListener(queues = "someQueue")
    public void processMessage(String content) {
        // ...
    }

}
```

**注** 具体参考[@EnableRabbit的Javadoc](https://docs.spring.io/spring-amqp/docs/current/api/org/springframework/amqp/rabbit/annotation/EnableRabbit.html)。

如果需要创建多个`RabbitListenerContainerFactory`实例，或想覆盖默认实例，你可以使用Spring Boot提供的`SimpleRabbitListenerContainerFactoryConfigurer`和`DirectRabbitListenerContainerFactoryConfigurer`，通过它们可以使用跟自动配置实例相同的配置初始化`SimpleRabbitListenerContainerFactory`。

**提示** 使用哪个容器无关紧要，自动配置将会暴露那两个bean。

例如，下面使用一个特殊的`MessageConverter`配置类创建了另一个factory：

```java
@Configuration
static class RabbitConfiguration {

    @Bean
    public SimpleRabbitListenerContainerFactory myFactory(
            SimpleRabbitListenerContainerFactoryConfigurer configurer) {
        SimpleRabbitListenerContainerFactory factory =
                new SimpleRabbitListenerContainerFactory();
        configurer.configure(factory, connectionFactory);
        factory.setMessageConverter(myMessageConverter());
        return factory;
    }

}
```

然后，你可以像下面那样在所有`@RabbitListener`注解方法中使用：

```java
@Component
public class MyBean {

    @RabbitListener(queues = "someQueue", containerFactory="myFactory")
    public void processMessage(String content) {
        // ...
    }

}
```

你可以启动重试处理那些监听器抛出异常的情况。默认地，`RejectAndDontRequeueRecoverer`被使用，但是你可以定义一个你自己的`MessageRecoverer`。当重试次数达到限制时，该消息将被拒绝，要不被丢弃，要不路由到一个dead-letter交换器，如果broker这样配置的话，默认禁用重试。

**重要** 默认的，如果禁用了重试，且监听器抛出异常，则Rabbit会无限期地进行重试。你可以采用两种方式修改该行为：设置`defaultRequeueRejected`属性为`false`，这样就不会重试，或者抛出一个`AmqpRejectAndDontRequeueException`异常表示该消息应该被拒绝。后面这个是开启重试，且达到最大重试次数时使用的策略。


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://jack80342.gitbook.io/spring-boot/iv.-spring-boot-features/32.-messaging/32.2-amqp/32.2.3-receiving-a-message.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
