RabbitMQ中的延迟消息

时间:2010-12-14 21:02:21

标签: rabbitmq

是否有可能通过RabbitMQ发送消息有一些延迟? 例如,我希望在30分钟后使客户端会话到期,并且我发送一条消息,该消息将在30分钟后处理。

8 个答案:

答案 0 :(得分:12)

随着RabbitMQ v2.8的发布,预定交付现已推出,但作为间接功能:http://www.javacodegeeks.com/2012/04/rabbitmq-scheduled-message-delivery.html

答案 1 :(得分:11)

您可以尝试两种方法:

旧方法:在每个消息/队列(策略)中设置TTL(生存时间)标头,然后引入DLQ来处理它。一旦ttl过期,您的消息将从DLQ移动到主队列,以便您的侦听器可以处理它。

最新方法:最近,RabbitMQ推出了 RabbitMQ延迟消息插件,使用它可以实现相同的功能,并且自RabbitMQ-3.5.8起支持此插件支持。< / p>

您可以使用x-delayed-message类型声明交换,然后使用自定义标头x-delay发布消息,以毫秒为单位表示消息的延迟时间。消息将在 x-delay 毫秒

之后传递到相应的队列
C:\Program Files (x86)\Microsoft Visual Studio\2017\Professional\MSBuild\Microsoft\NuGet\15.0\Microsoft.NuGet.targets(178,5): error : The package HockeySDK.Core with version 4.1.6 could not be found in C:\WINDOWS\system32\config\systemprofile\.nuget\packages\. Run a NuGet package restore to download the package. [C:\Program Files (x86)\Jenkins\workspace\MyApp\Weather\Weather.App.csproj]

更多信息:git

答案 2 :(得分:8)

感谢Norman的回答,我可以在NodeJS中实现它。

代码中的一切都很清楚。 希望它能节省一些人的时间。

var ch = channel;
ch.assertExchange("my_intermediate_exchange", 'fanout', {durable: false});
ch.assertExchange("my_final_delayed_exchange", 'fanout', {durable: false});

// setup intermediate queue which will never be listened.
// all messages are TTLed so when they are "dead", they come to another exchange
ch.assertQueue("my_intermediate_queue", {
      deadLetterExchange: "my_final_delayed_exchange",
      messageTtl: 5000, // 5sec
}, function (err, q) {
      ch.bindQueue(q.queue, "my_intermediate_exchange", '');
});

ch.assertQueue("my_final_delayed_queue", {}, function (err, q) {
      ch.bindQueue(q.queue, "my_final_delayed_exchange", '');

      ch.consume(q.queue, function (msg) {
          console.log("delayed - [x] %s", msg.content.toString());
      }, {noAck: true});
});

答案 3 :(得分:6)

由于我没有足够的声誉来添加评论,发布新的答案。这只是对http://www.javacodegeeks.com/2012/04/rabbitmq-scheduled-message-delivery.html

中已经讨论过的内容的补充

除了在消息上设置ttl之外,您可以在队列级别设置它。此外,您可以避免仅为了将消息重定向到不同的队列而创建新的交换。以下是示例java代码:

制片:

import com.rabbitmq.client.Channel;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.ConnectionFactory;
import java.util.HashMap;
import java.util.Map;

public class DelayedProducer {
    private final static String QUEUE_NAME = "ParkingQueue";
    private final static String DESTINATION_QUEUE_NAME = "DestinationQueue";

    public static void main(String[] args) throws Exception{
        ConnectionFactory connectionFactory = new ConnectionFactory();
        connectionFactory.setHost("localhost");
        Connection connection = connectionFactory.newConnection();
        Channel channel = connection.createChannel();

        Map<String, Object> arguments = new HashMap<String, Object>();
        arguments.put("x-message-ttl", 10000);
        arguments.put("x-dead-letter-exchange", "");
        arguments.put("x-dead-letter-routing-key", DESTINATION_QUEUE_NAME );
        channel.queueDeclare(QUEUE_NAME, false, false, false, arguments);

        for (int i=0; i<5; i++) {
            String message = "This is a sample message " + i;
            channel.basicPublish("", QUEUE_NAME, null, message.getBytes());
            System.out.println("message "+i+" got published to the queue!");
            Thread.sleep(3000);
        }

        channel.close();
        connection.close();
    }
}

消费者:

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;

public class Consumer {
   private final static String DESTINATION_QUEUE_NAME = "DestinationQueue";

    public static void main(String[] args) throws Exception{
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("localhost");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();

        channel.queueDeclare(QUEUE_NAME, false, false, false, null);
        System.out.println(" [*] Waiting for messages. To exit press CTRL+C");

        QueueingConsumer consumer = new QueueingConsumer(channel);
        boolean autoAck = false;
        channel.basicConsume(DESTINATION_QUEUE_NAME, autoAck, consumer);

        while (true) {
            QueueingConsumer.Delivery delivery = consumer.nextDelivery();
            String message = new String(delivery.getBody());
            System.out.println(" [x] Received '" + message + "'");
            channel.basicAck(delivery.getEnvelope().getDeliveryTag(), false);
        }

    }
}

答案 4 :(得分:6)

看起来this blog post描述了使用死信交换和消息ttl来做类似的事情。

下面的代码使用CoffeeScript和Node.JS来访问Rabbit并实现类似的东西。

amqp   = require 'amqp'
events = require 'events'
em     = new events.EventEmitter()
conn   = amqp.createConnection()

key = "send.later.#{new Date().getTime()}"
conn.on 'ready', ->
  conn.queue key, {
    arguments:{
      "x-dead-letter-exchange":"immediate"
    , "x-message-ttl": 5000
    , "x-expires": 6000
    }
  }, ->
    conn.publish key, {v:1}, {contentType:'application/json'}

  conn.exchange 'immediate'

  conn.queue 'right.now.queue', {
      autoDelete: false
    , durable: true
  }, (q) ->
    q.bind('immediate', 'right.now.queue')
    q.subscribe (msg, headers, deliveryInfo) ->
      console.log msg
      console.log headers

答案 5 :(得分:5)

目前无法做到这一点。您必须将过期时间戳存储在数据库或类似的东西中,然后有一个辅助程序来读取这些时间戳并对消息进行排队。

延迟消息是一种经常被请求的功能,因为它们在许多情况下都很有用。但是,如果您需要使客户端会话到期,我相信消息传递不是您理想的解决方案,而另一种方法可能会更好。

答案 6 :(得分:0)

  

假设您控制了消费者,您可以像这样实现对消费者的延迟??:

     

如果我们确定队列中的第n个消息总是具有比第n + 1个消息更小的延迟(对于许多用例来说都是如此):生产者在任务中发送timeInformation,传达此作业所需的时间要执行(currentTime + delay)。消费者:

     

1)从任务中读取scheduledTime

     

2)if currentTime&gt;预定时间继续。

     
    

Else delay = scheduledTime - currentTime

         
      

睡眠延迟指示的时间

    
  
     

使用者始终配置了并发参数。因此,其他消息将在队列中等待,直到消费者完成作业。所以,这个解决方案可以很好地工作,虽然它看起来很尴尬,特别是对于大的时间延迟。

答案 7 :(得分:0)

AMQP协议不支持延迟消息传递,但是通过使用Time-To-Live and Expiration Dead Letter Exchanges扩展名,可以实现延迟消息传递。此link中介绍了解决方案。我从该链接复制了以下步骤:

逐步:

Declare the delayed queue
    Add the x-dead-letter-exchange argument property, and set it to the default exchange "".
    Add the x-dead-letter-routing-key argument property, and set it to the name of the destination queue.
    Add the x-message-ttl argument property, and set it to the number of milliseconds you want to delay the message.
Subscribe to the destination queue

RabbitMQ repository on GitHub中还有一个用于延迟消息传递的插件。

请注意,有一个名为Celery的解决方案,它通过提供一个名为apply_async()的调用API,在RabbitMQ代理上支持延迟的任务排队。 Celery支持Python,node和PHP。