有没有办法使用.NET使用单个同步调用接收多条消息? 我见过question并且我找到了java类com.rabbitmq.client.QueueingConsumer,但我还没有在.NET命名空间中找到这样的客户端类(RabbitMQ.Client,RabbitMQ.Client.Events)
答案 0 :(得分:3)
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.
答案 1 :(得分:1)
感谢您的回答,但我找到了我要找的课程:RabbitMQ.Client.QueueingBasicConsumer
简单的实现是:
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;
}
当然,您可以使用Environment.TickCount
代替DateTime.Now