代码整合消息队列后,启动报错,出现rabbitMQ循环依赖的问题
异常信息:
┌─────┐
| rabbitTemplate defined in class path resource [org/springframework/boot/autoconfigure/amqp/RabbitAutoConfiguration$RabbitTemplateConfiguration.class]
↑ ↓
| myRabbitConfig (field org.springframework.amqp.rabbit.core.RabbitTemplate com.xxxx.gulimall.order.config.MyRabbitConfig.rabbitTemplate)
└─────┘
解决方法:
-
注释掉 @Autowired和@PostConstruct注解
-
自己给容器中放一个RabbitTemplate,参考RabbitAutoConfiguration$RabbitTemplateConfiguration.class
-
手动初始化模板方法
@Primary
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
this.rabbitTemplate = rabbitTemplate;
rabbitTemplate.setMessageConverter(messageConverter());
initRabbitTemplate();
return rabbitTemplate;
}
完整代码:
@Configuration
public class MyRabbitConfig {
RabbitTemplate rabbitTemplate;
@Primary
@Bean
public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) {
RabbitTemplate rabbitTemplate = new RabbitTemplate(connectionFactory);
this.rabbitTemplate = rabbitTemplate;
rabbitTemplate.setMessageConverter(messageConverter());
initRabbitTemplate();
return rabbitTemplate;
}
@Bean
public MessageConverter messageConverter() {
return new Jackson2JsonMessageConverter();
}
// @PostConstruct // MyRabbitConfig 对象创建完成以后,执行这个方法
public void initRabbitTemplate() {
rabbitTemplate.setConfirmCallback(new RabbitTemplate.ConfirmCallback() {
@Override
public void confirm(CorrelationData correlationData, boolean b, String s) {
System.out.println("confirm...correlationData=" + correlationData + ", b=" + b + ", s=" + s);
}
});
rabbitTemplate.setReturnCallback(new RabbitTemplate.ReturnCallback() {
@Override
public void returnedMessage(@Nullable Message message, int replyCode, @Nullable String replyText, @Nullable String exchange, @Nullable String routingKey) {
System.out.println("fail Message="+message+",replyCode="+replyCode+",replyText="+replyText +",exchange="+exchange+",routingKey="+routingKey);
}
});
}
}
版权声明:本文为shanghaibao123原创文章,遵循CC 4.0 BY-SA版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/shanghaibao123/article/details/120347631