如何使用@RabbitListener

时间:2018-07-02 20:13:02

标签: spring-boot spring-rabbitmq

我能够停止使用并重新启动使用,但是问题是,当我重新启动使用时,我能够处理已经发布的消息,但是当我发布新消息时,那些无法处理。 / p>

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Consumer;

@Component
public class RabbitMqueue implements Consumer {

int count = 0;

@RabbitListener(queues="dataQueue")
public void receivedData(@Payload Event msg, Channel channel, 
          @Header(AmqpHeaders.CONSUMER_TAG) String tag) throws IOException, 
                InterruptedException {

count++;
System.out.println("\n Message recieved from the Dataqueue is " + msg);

//Canceling consuming working fine.
if(count == 1) {
    channel.basicCancel(tag);
    System.out.println("Consumer is cancle");
}

count++;
System.out.println("\n count is " + count + "\n");

Thread.sleep(5000);

//restarting consumer. able to process already consumed messages
//but not able to see the newly published messages to the queue I mean
//newly published message is moving from ready to unack state but nothing 
//happening on the consumer side. 

if(count == 2) {
    channel.basicConsume("dataQueue", this);
            System.out.println("Consumer is started "); 
    }       
  }
}

2 个答案:

答案 0 :(得分:2)

您不得执行此channel.basicCancel(tag)

渠道/消费者由Spring管理;消费者参数唯一应该做的就是ack或nack消息(甚至很少用到-最好让容器来做ack)。

要停止/启动使用者,请使用端点注册表as described in the documentation

  

为注释创建的容器未在应用程序上下文中注册。您可以通过在getListenerContainers() bean上调用RabbitListenerEndpointRegistry获得所有容器的集合。然后,您可以遍历此集合,例如,停止/启动所有容器或在注册表本身上调用Lifecycle方法,这将在每个容器上调用操作。

例如registry.stop()将停止所有监听器。

  

您还可以使用getListenerContainer(String id)使用其ID获得对单个容器的引用;例如registry.getListenerContainer("multi")用于上面的代码段创建的容器。

答案 1 :(得分:1)

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

1)阻止在代码中启动:

@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;
}

2)阻止在app.yml / props中启动:

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

3)启动/停止单个听众

为您的@RabbitListener提供一个ID:

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

和:

@Autowired
private RabbitListenerEndpointRegistry rabbitListenerEndpointRegistry;

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