官术网_书友最值得收藏!

How to let queues expire

In this third case, the TTL is not related to messages anymore, but to queues. This case is a perfect fit to manage server restarts and updates. The RabbitMQ drops the queue as soon as the TTL has elapsed, that is, after the last consumer has stopped consuming messages.

As in the previous TTL-related recipes, you can find the Producer.java, Consumer.java, and GetOne.java files in Chapter02/Recipe03/Java/src/rmqexample.

Getting ready

To use this recipe, we need to set up the Java development environment as indicated in the Introduction section of Chapter 1, Working with AMQP.

How to do it...

As in the previous example, the extension regards only Consumer.java:

  1. Create or declare the exchange using the following code:
    channel.exchangeDeclare(exchange, "direct", false);
  2. Create or declare the queue, specifying a 30,000 milliseconds timeout to the x-expires optional argument as follows:
    Map<String, Object> arguments = new HashMap<String, Object>();
    arguments.put("x-expires", 30000);
    channel.queueDeclare(queue, false, false, false, arguments);
  3. Bind the queue to the exchange where messages are going to come from as follows:
    channel.queueBind(queue, exchange, routingKey);

How it works...

When we run either the Consumer.java or GetOne.java file, the timed queue is created and until there is a consumer attached to the queue or we call channel.basicGet(), it will continue to exist.

Only when we stop both the operations for at least 30 seconds, the queue is dropped and all the messages that it contains are lost.

Note

The queue is dropped independently from the fact that there are producers publishing messages to it or not.

In the course of the experiments, we can monitor the RabbitMQ queue status issuing rabbitmqctl list_queues and see this happening.

So, we can imagine a scenario where we have a statistics analysis program that needs to be restarted for an update of the code itself. It will restart without losing any messages, since its named queues will have a longer timeout. Alternatively, if we stop it, its queues will be deleted after the given TTL and worthless messages won't be stored at all.

主站蜘蛛池模板: 湾仔区| 巴楚县| 湖州市| 正定县| 镇赉县| 监利县| 沙田区| 玛纳斯县| 会同县| 成武县| 佛冈县| 瑞丽市| 常德市| 湖口县| 武夷山市| 柯坪县| 彭阳县| 绥德县| 台中市| 松潘县| 纳雍县| 双城市| 遵义县| 陇南市| 界首市| 崇明县| 永胜县| 隆回县| 巩留县| 库车县| 宜川县| 会昌县| 尖扎县| 平山县| 嘉禾县| 沁水县| 西华县| 两当县| 兴化市| 岗巴县| 青阳县|