RabbitMQ Consumer/Reciever无法在C# Windows Form中工作

ukxgm1gy  于 2023-10-20  发布在  RabbitMQ
关注(0)|答案(1)|浏览(154)

我目前正在使用rabbitMQ服务器,当我尝试在C#控制台应用程序中工作时,发布交换工作并成功保存在服务器中,消息将活跃地出现在控制台中,但当我在C# Windows窗体中应用我的源代码时,它不会获得发布者发送的所有消息。我把方法放在构造函数事件中,但根本没有发生,它不会收到任何消息。
请看下面的源代码

using Publisher;
using RabbitMQ.Client;
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows.Forms;
using System.Timers;
using RabbitMQ.Client.Events;
using System.Diagnostics;

namespace Consumer
{
    public partial class Consumer : Form
    {

        private EventingBasicConsumer consumer;
        ConnectionFactory factory;
        public Consumer()
        {
            factory = new ConnectionFactory() { HostName = Definition.HOSTNAME };
            using (var connection = factory.CreateConnection())
            using (var channel = connection.CreateModel())
            {
                channel.ExchangeDeclare(exchange: Definition.EXCHANGE, type: ExchangeType.Fanout);

                var queueName = channel.QueueDeclare().QueueName;
                channel.QueueBind(queue: queueName,
                                  exchange: Definition.EXCHANGE,
                                  routingKey: "");



                Debug.WriteLine(" [*] Waiting for Exchange ARexchange.");
                var consumer = new EventingBasicConsumer(channel);
                consumer.Received += (sender, ea) =>
                {
                   var body = ea.Body;
                   var message = Encoding.UTF8.GetString(body);
                   Debug.WriteLine(" [x] {0}", message);
                 };
                channel.BasicConsume(
                                queueName,
                                 autoAck: false,
                                 consumer: consumer);
            }

            InitializeComponent();

        }

        private void Consumer_Load(object sender, EventArgs e)
        {

        }
        private void setExchange()
        {
            lblExchange.Text = Definition.EXCHANGE;
        }

    }
}
yuvru6vn

yuvru6vn1#

请读一下这个:https://learn.microsoft.com/en-us/dotnet/csharp/language-reference/keywords/using-statement

using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())

当这些using语句退出时,通道和连接将关闭。更改代码,将它们作为示例变量保存到Consumer类中。然后,当表单退出时,可以清理这两个示例。
如果你在一个可以克隆、编译和运行的仓库中提供代码,人们可以通过提交拉取请求来帮助你改进代码。

相关问题