如何让IModel.BasicAcks解雇?

时间:2011-04-26 00:27:36

标签: c# .net rabbitmq

我第一次玩RabbitMQ的.NET API,我想出了一个看似合理的用例:我想创建发布消息的发布者,并在他们被Ack-ed之后做一些事情。 IModel.BasicAcks事件似乎是了解这一点的好方法,所以 -

我写了一个出版商:

       private static void Post(string message) {

            model.ExchangeDeclare("MyExchange", ExchangeType.Fanout, true);
            model.QueueDeclare("MyQueue", true, false, false, null);
            model.QueueBind("MyQueue", "MyExchange", "", new Dictionary<string, object>());

            byte[] messageBodyBytes = System.Text.UTF8Encoding.ASCII.GetBytes(message);
            IBasicProperties props = model.CreateBasicProperties();
            props.ContentType = "text/plain";
            props.DeliveryMode = 2;
            model.BasicPublish("MyExchange", "", props, messageBodyBytes);
    }

订阅者:

    private static void Receive() {
            var gotten = model.BasicGet("MyQueue", false);
            var text = System.Text.UTF8Encoding.ASCII.GetString(gotten.Body);
            Console.WriteLine(text);
            model.BasicAck(gotten.DeliveryTag, false);
    }

这是Console App的入口点:

        static void Main(string[] args) {

        connectionFactory = new ConnectionFactory();
        connectionFactory.HostName = "localhost";
        connection = connectionFactory.CreateConnection();
        model = connection.CreateModel();
        model.BasicAcks += new RabbitMQ.Client.Events.BasicAckEventHandler(model_BasicAcks);
        Post("Hello, World!");
        Receive();
        Console.ReadKey();

        connection.Dispose();
        model.Dispose();

    }

由于某种原因,我的事件处理程序没有被调用。 “Hello,World!”消息被发布,读取,Acked并打印到控制台,但由于某种原因,永远不会调用事件处理程序。

我做错了吗?订阅IModel.ModelShutdown似乎工作正常。

2 个答案:

答案 0 :(得分:3)

我会将好奇心引用到RabbitMQ团队对此问题的回应。

Here's what they had to say

简而言之,事件即将发生,但这不是我认为的可能 - 这是发布者确认,explained in this RabbitMQ blog post

答案 1 :(得分:0)

经过大量的api实验后,这对我有用。在声明我的交换和队列之前,我需要声明我的事件处理程序。

_rabbitMqChannel.BasicAcks += new BasicAckEventHandler(_rabbitMqChannel_BasicAcks);
_rabbitMqChannel.BasicNacks += new BasicNackEventHandler(_rabbitMqChannel_BasicNacks);

_rabbitMqChannel.ExchangeDeclare(ExchangeName, ExchangeTypeVal.ToString());
_rabbitMqChannel.QueueDeclare(QueueName, QueueDurable, QueueExclusive, QueueDelete, null);
_rabbitMqChannel.QueueBind(QueueName, ExchangeName, RoutingKey);

以下是事件处理程序方法的外观......

private void _rabbitMqChannel_BasicNacks(IModel model, BasicNackEventArgs args)
{
    throw new NotImplementedException();
}

private void _rabbitMqChannel_BasicAcks(IModel model, BasicAckEventArgs args)
{
    throw new NotImplementedException();
}

花了半天时间!!希望这对某人有所帮助;)