File tree Expand file tree Collapse file tree 1 file changed +51
-1
lines changed
Expand file tree Collapse file tree 1 file changed +51
-1
lines changed Original file line number Diff line number Diff line change 1- ###32 .2.3 Receiving a message
1+ ###32 .2.3 接收消息
2+ 当Rabbit设施出现时,所有bean都可以注解` @RabbitListener ` 来创建一个监听器端点。如果没有定义` RabbitListenerContainerFactory ` ,Spring Boot将自动配置一个默认的。如果定义` MessageConverter ` beans,它将自动关联到默认的factory。
3+
4+ 下面的组件创建一个` someQueue ` 队列上的监听器端点:
5+ ``` java
6+ @Component
7+ public class MyBean {
8+
9+ @RabbitListener (queues = " someQueue" )
10+ public void processMessage (String content ) {
11+ // ...
12+ }
13+
14+ }
15+ ```
16+ ** 注** 具体参考[ @EnableRabbit ] ( http://docs.spring.io/spring-amqp/docs/current/api/org/springframework/amqp/rabbit/annotation/EnableRabbit.html ) 。
17+
18+ 如果需要创建多个` RabbitListenerContainerFactory ` 实例,或想覆盖默认实例,你可以使用Spring Boot提供的` SimpleRabbitListenerContainerFactoryConfigurer ` ,通过它可以使用跟自动配置实例相同的配置初始化` SimpleRabbitListenerContainerFactory ` 。
19+
20+ 例如,下面使用一个特殊的` MessageConverter ` 创建了另一个factory:
21+ ``` java
22+ @Configuration
23+ static class RabbitConfiguration {
24+
25+ @Bean
26+ public SimpleRabbitListenerContainerFactory myFactory (
27+ SimpleRabbitListenerContainerFactoryConfigurer configurer ) {
28+ SimpleRabbitListenerContainerFactory factory =
29+ new SimpleRabbitListenerContainerFactory ();
30+ configurer. configure(factory, connectionFactory);
31+ factory. setMessageConverter(myMessageConverter());
32+ return factory;
33+ }
34+
35+ }
36+ ```
37+ 然后,你可以像下面那样在所有` @RabbitListener ` 注解方法中使用:
38+ ``` java
39+ @Component
40+ public class MyBean {
41+
42+ @RabbitListener (queues = " someQueue" , containerFactory = " myFactory" )
43+ public void processMessage (String content ) {
44+ // ...
45+ }
46+
47+ }
48+ ```
49+ 你可以启动重试处理那些监听器抛出异常的情况,当重试次数达到限制时,该消息将被拒绝,要不被丢弃,要不路由到一个dead-letter交换器,如果broker这样配置的话,默认禁用重试。
50+
51+ ** 重要** 如果没启用重试,且监听器抛出异常,则Rabbit会不定期进行重试。你可以采用两种方式修改该行为:设置` defaultRequeueRejected ` 属性为` false ` ,这样就不会重试;或抛出一个` AmqpRejectAndDontRequeueException ` 异常表示该消息应该被拒绝,这是开启重试,且达到最大重试次数时使用的策略。
You can’t perform that action at this time.
0 commit comments