gpt4 book ai didi

java - 处理 RabbitMQ Spring Boot 应用程序中的异常

转载 作者:行者123 更新时间:2023-12-02 05:02:03 34 4
gpt4 key购买 nike

我正在使用 Spring Boot 1.4.1-RELEASE 和 RabbitMQ 3.2.3。我的应用程序类看起来像这样 -

@SpringBootApplication
@EnableAutoConfiguration
public class EventStoreMessageDeliveryApplication {

public final static String queueName = "customer.default.queue"; // spring-boot

@Bean
Queue queue() {
return new Queue(queueName, true);
}

@Bean
FanoutExchange exchange() {

return new FanoutExchange("customer.events.fanout.exchange", true, false); // spring-boot-exchange
}

@Bean
Binding binding() {

return new Binding(queueName, Binding.DestinationType.QUEUE, "customer.events.fanout.exchange", "*.*", null);
}

@Bean
public ConnectionFactory connectionFactory() {

CachingConnectionFactory connectionFactory = new CachingConnectionFactory("localhost");
connectionFactory.setPublisherConfirms(true);

return connectionFactory;
}

@Bean
SimpleMessageListenerContainer container(MessageListenerAdapter listenerAdapter) {

SimpleMessageListenerContainer container = new SimpleMessageListenerContainer();
container.setConnectionFactory(connectionFactory());
container.setQueueNames(queueName);
container.setMessageListener(listenerAdapter);
container.setRecoveryBackOff(new ExponentialBackOff(3000, 2));
return container;
}

@Bean
MessageListenerAdapter listenerAdapter(Receiver receiver) {

return new MessageListenerAdapter(receiver, "receiveMessage");
}

public static void main(String[] args) throws InterruptedException {

SpringApplication.run(EventStoreMessageDeliveryApplication.class, args);
}
}

我的监听器类看起来像 -

@Component
public class Receiver {

private CountDownLatch latch = new CountDownLatch(1);

public void receiveMessage(String message) {

System.out.println("Received <" + message + ">");

// do something

latch.countDown();
}

public CountDownLatch getLatch() {

return latch;
}

}

我想处理代理关闭时可能出现的异常,例如连接被拒绝。我该如何处理此类异常?我不确定在哪里可以获取异常的句柄。

最佳答案

您可以创建一个SimpleRabbitListenerContainerFactory。这基本上是 RabbitConnectionFactory 事件的监听器。

@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory() {
SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
factory.setConnectionFactory(connectionFactory());
factory.setErrorHandler(rabbitErrorHandler());
return factory;
}

rabbitErrorHandler()可以返回org.springframework.util.ErrorHandler实现的bean。

引用docs

关于java - 处理 RabbitMQ Spring Boot 应用程序中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43867088/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com