Rabbitmq retrieve multiple messages using single synchronous call using .NET

你离开我真会死。 提交于 2020-01-02 03:58:04

问题


Is there a way to receive multiple message using a single synchronous call using .NET?
I've seen question and I've found java class com.rabbitmq.client.QueueingConsumer, but I haven't found such client class in .NET namespaces (RabbitMQ.Client, RabbitMQ.Client.Events)


回答1:


You can retrieve as many messages as you want using the BasicQoS.PrefetchCount:

var model = _rabbitConnection.CreateModel();
// Configure the Quality of service for the model. Below is how what each setting means.
// BasicQos(0="Dont send me a new message untill I’ve finshed",  _fetchSize = "Send me N messages at a time", false ="Apply to this Model only")
model.BasicQos(0, fetchSize, false);

Note: if you set fetchSize = 20 then it will retrieve the first 20 messages that are currently in the queue. But, once the queue has been emptied it won't wait for 20 messages to build up in the queue, it will start consuming them as fast as possible, grabbing up to 20 at a time.

Hopefully that makes sense.




回答2:


Thanks for answers, but I've found the class which I looked for: RabbitMQ.Client.QueueingBasicConsumer
Simple implementation is:

IEnumerable<T> Get(int maxBatchCount, int getMessageTimeout, int getBatchTimeout)
{
    var result = new List<T>();
    var startTime = DateTime.Now;
    while (result.Count < maxBatchCount)
    {
        var deliverEventArgs = new BasicDeliverEventArgs();
        if ((_consumer as QueueingBasicConsumer).Queue.Dequeue(GetMessageTimeout, out deliverEventArgs))
        {
            var entry = ContractSerializer.Deserialize<T>(deliverEventArgs.Body);
            result.Add(entry);
            _queue.Channel.BasicAck(deliverEventArgs.DeliveryTag, false);
        }
        else
            break;

        if ((DateTime.Now - startTime) >= TimeSpan.FromMilliseconds(getBatchTimeout))
            break;
    }
    return result;
}

Well, of course, you can use Environment.TickCount instead of DateTime.Now



来源:https://stackoverflow.com/questions/32309155/rabbitmq-retrieve-multiple-messages-using-single-synchronous-call-using-net

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!