等到收到消息后再使用C#RabbitMQ传递消息正文

时间:2017-11-16 12:59:17

标签: c# multithreading rabbitmq

我想从队列中读取消息,并且一旦可用就想在消费者类之外发送byte []。

public byte[] Receive()
{
    if (messagingAdapter == null)
        return default(byte[]);

    byte[] messageBody = null;
    var channel = messagingAdapter.GetChannel();
    channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
    using (var subscription = new Subscription(channel, containerName, false))
    {
        while (channel.IsOpen)
        {
            var success = subscription.Next(5000, out BasicDeliverEventArgs eventArgs);
            if (success == false) continue;
            messageBody = eventArgs.Body;
            channel.BasicAck(eventArgs.DeliveryTag, false);
        }
    }
    return messageBody;
}

在上面的代码中,有两个问题(可以更多)。

1)即使在写入prefetchCount = 1之后,它仍然会读取所有消息。 2)等待5秒后,我从未获得成功,而且我无法将身体送到外面。

我已经写了一个代码,它做了同样的事情,但是在帖子本身,它被写成不建议做的方式。

示例代码:

using (var signal = new ManualResetEvent(false))
{
    var consumer = new EventingBasicConsumer(channel);

    consumer.Received +=

    (sender, args) =>
    {
        messageBody = args.Body;
        signal.Set();
    };
    //// start consuming
    channel.BasicConsume(containerName, true, consumer);
    // wait until message is received or timeout reached
    bool timeout = !signal.WaitOne(TimeSpan.FromSeconds(10));
    // cancel subscription
    channel.BasicCancel(consumer.ConsumerTag);
    if (timeout)
    {
        // timeout reached - do what you need in this case
        throw new Exception("timeout");
    }
    return messageBody;
    // at this point messageBody is received
}

1 个答案:

答案 0 :(得分:0)

请尝试使用channel.BasicGet阅读,例如:

private byte[] ReadRabbitMsg(IModel channel, string queue)
{
    if (channel.MessageCount(queue) == 0) return null;
    BasicGetResult result = channel.BasicGet(queue, true);
    if (result == null) return null;
    else
    {
        IBasicProperties props = result.BasicProperties;
        byte[] buff = result.Body;
    }
}