使用java停止队列侦听RabbitMQ

时间:2014-12-24 02:32:54

标签: java rabbitmq message-queue

您好我在我的java应用程序中使用rabbitMQ。当我停止应用程序时,我需要确保在停止应用程序之前停止队列侦听器(停止从队列接收消息)。 我不确定是否需要拨打 channel.close() channel.basicCancel(" tag")。 编写以下代码以停止队列侦听。

if(myContext.myChannel.isOpen()){ 

  //myChannel is the one I am using to listen to queue 
  myContext.myChannel.basicCancel("OP"); 

  //myContext.myChannel.close(); 
}else{ 
   return ok("Channel is not open"); 
}

2 个答案:

答案 0 :(得分:4)

如果你想要停止听众,你必须:

 Connection connection = factory.newConnection();
 Channel channel = connection.createChannel();
 channel.queueDeclare("myQueue", false, false, false, null);
 MyConsumer consumer = new MyConsumer(channel);
 String consumerTag = channel.basicConsume("myQueue", false, consumer);
 System.out.println("press any key to terminate");
 System.in.read();

 channel.basicCancel(consumerTag);<----- this stop listening
 channel.close(); <--- this close the channel and eventually all listening
 connection.close();<-- this close the connection and all channels 

请阅读有关"isOpen"方法的信息:https://www.rabbitmq.com/api-guide.html

  

不使用通道和连接对象的isOpen()方法   推荐用于生产代码,因为返回的值   方法取决于是否存在关闭原因。

答案 1 :(得分:0)

如果您使用的是AMQP /兔子,则可以尝试以下方法之一:

@Bean
public SimpleRabbitListenerContainerFactory rabbitListenerContainerFactory(ConnectionFactory connectionFactory) {
    SimpleRabbitListenerContainerFactory factory = new SimpleRabbitListenerContainerFactory();
    factory.setConnectionFactory(connectionFactory);

    //
    //autoStartup = false, prevents handling messages immedeatly. You need to start each listener itselve. 
    //
    factory.setAutoStartup(false); 

    factory.setMessageConverter(new Jackson2JsonMessageConverter());
    return factory;
}

或在app.yml / props中:

rabbitmq.listener.auto-startup: false
rabbitmq.listener.simple.auto-startup: false

或: 给您的@RabbitListener一个ID

@RabbitListener(queues = "myQ", id = "myQ")
...

和:

@Autowired
private RabbitListenerEndpointRegistry rabbitListenerEndpointRegistry;

MessageListenerContainer listener = 
   rabbitListenerEndpointRegistry.getListenerContainer("myQ");
    ...
listener.start();
...
listener.stop();