RabbitMQ中的消息丢失

时间:2014-09-12 12:17:02

标签: java persistence rabbitmq message-queue

我尝试构建持久消息队列,每条消息有一些延迟。在Java代码中,它看起来像这样:

    ConnectionFactory factory = new ConnectionFactory();
    factory.setHost("localhost");
    Connection connection = factory.newConnection();
    Channel channel = connection.createChannel();

    channel.exchangeDeclare("WorkExchange", "direct");
    channel.queueDeclare("WorkQueue", true, false, false, null);
    channel.queueBind("WorkQueue", "WorkExchange", "");

    Map<String, Object> args = new HashMap<>();
    args.put("x-dead-letter-exchange", "WorkExchange");

    channel.exchangeDeclare("RetryExchange", "direct");
    channel.queueDeclare("RetryQueue", true, false, false, args);
    channel.queueBind("RetryQueue", "RetryExchange", "");

    channel.confirmSelect();
    BasicProperties properties = new BasicProperties();
    properties.setDeliveryMode(2);
    properties.setExpiration("120000");
    channel.basicPublish("RetryExchange", "", properties, "Hello world!".getBytes());
    channel.waitForConfirmsOrDie();
    connection.close();

但是,我有一些持久性问题。当我停止服务器时,等待一段时间再次启动它,必须移动到WorkQueue的消息才会消失。我做错了什么?或者它是设计的?

1 个答案:

答案 0 :(得分:6)

  

但是,我有一些持久性问题。当我停止服务器时,请等一段时间再次启动它,      必须移动到WorkQueue的消息才会消失。我做错了什么?或者它是设计的?

您应该使用 MessageProperties 来保持邮件持久性。

channel.basicPublish("", "task_queue", 
        MessageProperties.PERSISTENT_TEXT_PLAIN,
        message.getBytes());

您当前的代码`channel.queueDeclare(&#34; RetryQueue&#34;, true ,false,false,args);将使队列持久化而不是消息。

更多RabbitMQ Doc