2011-03-28 49 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