在春天对rabbitmq监听器的异常处理

时间:2017-04-04 13:39:33

标签: spring-mvc rabbitmq spring-rabbitmq

春天工作,我是rabbitmq的新手,我想知道我错在哪里。

我编写了一个rabbitmq连接工厂和一个包含监听器的监听器容器。我还为监听器容器提供了一个错误处理程序,但它似乎没有用。

我的春豆:

<div class='wrapper'>
  <div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div><!--You can remove the white-space by adding a comment between the elements
  --><div class='item-2'>
    <h1>Title 1</h1>
    <div class='demo'>
    </div>
  </div>
</div>

这是我的RabbitMQErrorHandler类:

<script>
var app = angular.module("myapp",[]);

app.controller("usercontroller",function($scope,$http){
$scope.insertData = function(){
  $http.post(
    "insert.php",    
    {'yourName':$scope.yourName, 'lstName':$scope.lstName,
 'passwrd':$scope.passwrd}).success(function(data){
      alert(data);
    });
}
});

我假设,如果我向连接工厂提供无效凭据,应该执行RabbitMQErrorHandler类的handleError方法,并且服务器应该正常启动,但是,当我尝试运行服务器时,该方法不会执行(在控制台中抛出异常)并且服务器无法启动。我在哪里错过了什么以及可能是什么?

1 个答案:

答案 0 :(得分:3)

错误处理程序用于在邮件传递期间处理错误;由于您还没有连接,因此没有消息可以处理错误。

要获取连接异常,您应该实现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);
    }

}