2011-03-28 373 views
0

这是我的代码,并且我在autoDelete上设置了true这两个队列,交换机终于发布了,此时几分钟内不向消费者发送任何消息,我希望自动停止消费者端也许你完全不理解我的句子。如何在RABBITMQ中为消费者端设置时间

我如何设置,它^^

和我怎么在服务器端得到的文档对象(DOC)

public void initConsumer() { 
    try { 
    ConnectionFactory factory = new ConnectionFactory(); 
    Connection connection = factory.newConnection(); 
    Channel channel = connection.createChannel(); 
    channel.queueDeclare(this.queueName, this.maintain, false, this.queueAutoDelete, null); 
    channel.exchangeDeclare(this.exchangeName, this.exchangeType, this.maintain, this.exchangeAutoDelete, null); 
    channel.queueBind(this.queueName, this.exchangeName, this.routingKey); 
    QueueingConsumer consumer = new QueueingConsumer(channel); 
    channel.basicConsume(this.queueName, false, consumer); 
    while (true) { 

    QueueingConsumer.Delivery delivery = consumer.nextDelivery(); 

    System.out.println(" [x] Received " 
     + new String(delivery.getBody())); 

    channel 
     .basicAck(delivery.getEnvelope().getDeliveryTag(), 
     false); 
    } 
    } catch (Exception e) { 
    System.out.println("Exception error at initConsumer()"); 
    } 
} 
+0

我想你所问的是:“如果我的消费者在几分钟内没有收到经纪人的任何消息,我该如何让消费者自动关机?”那是对的吗? – 2011-03-30 22:24:48

+0

yes没有收到来自经纪商的任何消息。 – BillyLee 2011-04-01 05:52:42

+0

那时候我想停止消费者方。并设置观看时间。 – BillyLee 2011-04-01 05:53:47

回答

5

你可以使用nextDelivery(重载版本),其中有一个超时参数:

QueueingConsumer.Delivery delivery = null; 
long timeout = 2 * 60 * 1000; // 2 minutes in milliseconds 
delivery = queuingConsumer.nextDelivery(timeout); 
if (delivery == null) { 
    // shut down your consumer here - no events arrived 
    // before the timeout was reached 
} 
else { 
    // process the delivered message here 
} 

希望有帮助。

+0

非常感谢你。请原谅我的答复。 – BillyLee 2011-04-12 08:32:02

+0

没问题。如果它适合您,请随时接受答案。 – 2011-04-12 14:36:39

+0

@BrianKelly:将超时设置为零意味着无需等待接收? – 2013-05-30 11:41:13