错误:
Only one ConfirmCallback is supported by each RabbitTemplate] with root cause
原因:
因为Spring的Bean默认都是单例;而RabbitTemplate对象同样支持一个回调。
解决:使用@Scope("prototype")可通知Spring将被注解的Bean变为多例。
代码:
// 改RabbitTemplate为多例 @Bean @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) { RabbitTemplate template = new RabbitTemplate(connectionFactory); template.setMandatory(true); template.setMessageConverter(new SerializerMessageConverter()); return template; }
或:
@Bean @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) public RabbitTemplate.ConfirmCallback confirmCallback(){ RabbitTemplate.ConfirmCallback confirmCallback = new RabbitTemplate.ConfirmCallback() { @Override public void confirm(CorrelationData correlationData, boolean ack, String cause) { System.out.println("----------进入了confirmCallback方法---------"); System.out.println("回调id:" + correlationData); System.out.println("确认情况:" + ack); System.out.println("原因:" + cause); if(ack){ System.out.println("消息发送成功"); }else{ System.out.println("消息未进入交换机,保存到数据库,定时任务重发"); } } }; return confirmCallback; } @Bean @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) public RabbitTemplate.ReturnsCallback returnsCallback(){ RabbitTemplate.ReturnsCallback returnsCallback = new RabbitTemplate.ReturnsCallback(){ @Override public void returnedMessage(ReturnedMessage returned) { System.out.println("----------进入了returnsCallback方法---------"); int code = returned.getReplyCode(); System.out.println("相应码==>"+code); String replyText = returned.getReplyText(); System.out.println("响应原因==>"+replyText); System.out.println("returned==>"+returned); } }; return returnsCallback; } @Bean @Scope(value = ConfigurableBeanFactory.SCOPE_PROTOTYPE) public RabbitTemplate rabbitTemplate(ConnectionFactory connectionFactory) { RabbitTemplate template = new RabbitTemplate(connectionFactory); template.setMandatory(true); // template.setConfirmCallback(confirmCallback()); // template.setReturnsCallback(returnsCallback()); return template; }
标签:RabbitTemplate,ConfirmCallback,supported,System,template,println,cause,out From: https://www.cnblogs.com/warmNest-llb/p/17983281