使用 spring,我是 rabbitmq 的新手,我想知道我哪里错了。
我已经编写了一个 rabbitmq 连接工厂和一个包含监听器的监听器容器。我还为监听器容器提供了错误处理程序,但它似乎不起作用。
我的 Spring Bean :
<rabbit:connection-factory id="RabbitMQConnectionFactory" virtual-host="${rabbitmq.vhost}" host="${rabbitmq.host}" port="${rabbitmq.port}" username="${rabbitmq.username}" password="${rabbitmq.password}"/>
<rabbit:listener-container missing-queues-fatal="false" declaration-retries="0" error-handler="errorHandlinginRabbitMQ" recovery-interval="10000" auto-startup="${rabbitmq.apc.autostartup}" max-concurrency="1" prefetch="1" concurrency="1" connection-factory="RabbitMQConnectionFactory" acknowledge="manual">
<rabbit:listener ref="apcRabbitMQListener" queue-names="${queue.tpg.rabbitmq.destination.apc}" exclusive="true" />
</rabbit:listener-container>
<bean id="errorHandlinginRabbitMQ" class="RabbitMQErrorHandler"/>
这是我的 RabbitMQErrorHandler 类:
public class RabbitMQErrorHandler implements ErrorHandler
{
@Override
public void handleError(final Throwable exception)
{
System.out.println("error occurred in message listener and handled in error handler" + exception.toString());
}
}
我假设的是,如果我向连接工厂提供无效凭据,则 RabbitMQErrorHandler 类的 handleError 方法应该执行,并且服务器应该正常启动,但是,当我尝试运行服务器时,该方法不会执行(控制台中抛出异常)并且服务器无法启动。我在哪里遗漏了什么?
请您参考如下方法:
错误处理程序用于处理消息传递过程中的错误;由于您尚未连接,因此没有要处理错误的消息。
要获得连接异常,你应该实现ApplicationListener<ListenerContainerConsumerFailedEvent>如果您将失败作为一个 bean 添加到应用程序上下文中,您将收到失败作为事件。
如果您实现 ApplicationListener<AmqpEvent>,您将获得其他事件(消费者启动、消费者停止等) .
编辑
<rabbit:listener-container auto-startup="false">
<rabbit:listener id="fooContainer" ref="foo" method="handleMessage"
queue-names="si.test.queue" />
</rabbit:listener-container>
<bean id="foo" class="com.example.Foo" />
富:
public class Foo {
public final CountDownLatch latch = new CountDownLatch(1);
public void handleMessage(String foo) {
System.out.println(foo);
this.latch.countDown();
}
}
应用:
@SpringBootApplication
@ImportResource("context.xml")
public class So43208940Application implements CommandLineRunner {
public static void main(String[] args) {
ConfigurableApplicationContext context = SpringApplication.run(So43208940Application.class, args);
context.close();
}
@Autowired
private SimpleMessageListenerContainer fooContainer;
@Autowired
private CachingConnectionFactory connectionFactory;
@Autowired
private RabbitTemplate template;
@Autowired
private Foo foo;
@Override
public void run(String... args) throws Exception {
this.connectionFactory.setUsername("junk");
try {
this.fooContainer.start();
}
catch (Exception e) {
e.printStackTrace();
}
Thread.sleep(5000);
this.connectionFactory.setUsername("guest");
this.fooContainer.start();
System.out.println("Container started");
this.template.convertAndSend("si.test.queue", "foo");
foo.latch.await(10, TimeUnit.SECONDS);
}
}


