RabbitMQ异常案例数据

时间:2016-08-24 13:54:36

标签: c# rabbitmq

我是RabbitMQ的新手并且做了第一次申请。但我对异常情况有点困惑。例如,我从Queue收到一条消息。在将数据保存到数据库时发生错误。数据将会丢失。这个问题的解决方案是什么?

        var factory = new ConnectionFactory { HostName = "10.1.2.34" };

        using (var connection = factory.CreateConnection())
        {
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: "business.orders", durable: false, exclusive: false, autoDelete: false, arguments: null);

                var data = channel.BasicGet(queue: "business.orders", noAck: true);

                using (var stream = new MemoryStream(data.Body))
                {
                    var order = (PlaceOrder)new BinaryFormatter().Deserialize(stream);

                    // Throw exception. ????
                }
            }
        }

1 个答案:

答案 0 :(得分:1)

您必须使用手册ack

var data = channel.BasicGet(queue: "business.orders", noAck: false);

如果您没有错误,请插入数据库:

channel.BasicAck(result.DeliveryTag, false);

请在此处阅读:https://www.rabbitmq.com/dotnet-api-guide.html

bool noAck = false;
BasicGetResult result = channel.BasicGet(queueName, noAck);
if (result == null) {
    // No message available at this time.
} else {
    IBasicProperties props = result.BasicProperties;
    byte[] body = result.Body;
    ...
Since noAck = false above, you must also call IModel.BasicAck to acknowledge that you have successfully received and processed the message:
    ...
    // acknowledge receipt of the message
    channel.BasicAck(result.DeliveryTag, false);
}

btw我建议你阅读:https://www.rabbitmq.com/dotnet-api-guide.html部分:

按订阅检索邮件("推送API")

basicGetEventingBasicConsumer

的影响较慢