RabbitMQ.Client BasicPublish在完成之前返回

时间:2018-12-22 00:18:01

标签: c# rabbitmq

我遇到一个问题,我有一个作为预定任务运行的控制台应用程序,它向Rabbit队列发送了约35万条消息,处理了队列并结束了。我的问题是,在消息实际上完全发布之前,model.BasicPublish返回,并且在调用model.Close时,它最终超时了。我注意到的另一件事是,在应用程序结束并关闭后,Rabbit Management UI表示交换仍在接收消息约30-45秒。我正在使用5.1.0的RabbitMQ.Client块软件包

代码非常简单,并且可以复制/粘贴(用户名/密码除外)

        var connectionFactory = new ConnectionFactory();
        connectionFactory.HostName = "localhost";
        connectionFactory.Password = "pass";
        connectionFactory.UserName = "user";
        connectionFactory.VirtualHost = "test";

        var connection = connectionFactory.CreateConnection();
        var model = connection.CreateModel();

        model.QueuePurge("x");

        var fileLines = File.ReadAllLines(@"bigfile.txt");
        var accounts = fileLines.Select(x => x.Split(',').FirstOrDefault()).Where(x => !string.IsNullOrWhiteSpace(x));
        var watch = new Stopwatch();
        watch.Start();
        Console.WriteLine("Start: " + DateTime.Now);
        foreach (var account in accounts)
        {
            var bytes = Encoding.Default.GetBytes(account);
            model.BasicPublish("incoming", "", null, bytes);
        }
        Console.WriteLine("Done: " + DateTime.Now);
        Console.WriteLine("Time: " + watch.Elapsed);
        try
        {
            model.Close();
        }
        catch (Exception exception)
        {
            Console.WriteLine("Error: " + exception);
        }

我的兔子配置用于队列和交换:

{
    "rabbit_version": "3.7.7",
    "policies": [],
    "queues": [
        {
            "name": "x",
            "durable": false,
            "auto_delete": false,
            "arguments": {}
        }
    ],
    "exchanges": [
        {
            "name": "incoming",
            "type": "direct",
            "durable": false,
            "auto_delete": false,
            "internal": false,
            "arguments": {}
        }
    ],
    "bindings": [
        {
            "source": "incoming",
            "destination": "x",
            "destination_type": "queue",
            "routing_key": "",
            "arguments": {}
        }
    ]
}

foreach块大约需要14秒钟。

有人对如何使其正常工作有任何想法吗?预先感谢。

1 个答案:

答案 0 :(得分:1)

  

Rabbit Management UI表示交易所仍在接收消息   持续约30-45秒

那是由于网络数据缓冲。

  

我的问题是model.BasicPublish在返回之前   消息实际上已完全发布,并且在model.Close为   叫做结束超时

在这种情况下,您应该启用发布者确认(通过ConfirmSelectWaitForConfirms),并且只有在确认所有发布的消息之后才关闭模型。


注意: RabbitMQ团队监视the rabbitmq-users mailing list,并且有时仅在StackOverflow上回答问题。