从Windows服务访问新的RabbitMQ消息

问题描述 投票:0回答:1

我正在尝试使用Windows服务从RabbitMQ读取新消息,但不会触发接收新消息的事件。该服务可以在调试模式下作为控制台应用程序启动。在这种情况下,该事件将触发,我可以阅读新消息。该服务与我用来登录Windows的用户一起启动。这是OnStart服务事件处理程序中代码的一部分

var factory = new ConnectionFactory() { HostName = "localhost" };
                using (var conn = factory.CreateConnection())
                {
                    using (var channel = conn.CreateModel())
                    {
                        channel.ExchangeDeclare("sm_posts", "fanout");
                        var argu = new Dictionary<string, object>();
                        argu.Add("x-max-length", 10000);

                        var consumerQueue = channel.QueueDeclare().QueueName;
                        channel.QueueBind(queue: consumerQueue, exchange: "sm_posts", routingKey: "");
                        var consumer = new EventingBasicConsumer(channel);

                        log.Info("Waiting for new messages...");

                        consumer.Received += (model, ea) =>
                        {
                            count++;
                            var body = ea.Body;
                            var message = Encoding.UTF8.GetString(body);

                            log.Info(message + "\n\n\n\n\n");

为什么Windows服务不接收消息,而在调试模式下将其作为控制台应用程序启动时却接收消息?

c# windows-services rabbitmq
1个回答
0
投票
private static ConnectionFactory _factory; private static IConnection _connection; private static IModel _channel; private static EventingBasicConsumer _consumer;

然后可以使用OnStart方法创建连接和通道对象,即

    protected override void OnStart(string[] args)
            {
                _factory = new ConnectionFactory()
                {
                    HostName = "Host",
                    UserName = "username",
                    Password = "password"
                };
                _connection = _factory.CreateConnection();
                _channel = _connection.CreateModel();

                _channel.QueueDeclare(queue: _queueName, durable: false, exclusive: false,autoDelete: false, arguments: null);

                _consumer = new EventingBasicConsumer(_channel);

                _consumer.Received += (s, ev) =>
                {
                    //Handle messages here.
                };

                _channel.BasicConsume(queue: _queueName, autoAck: true, consumer: _consumer);
            }

最后不要忘了在Windows服务停止时释放并关闭连接和通道。

 protected override void OnStop()
        {
            _channel.Close();
            _connection.Close();
            _channel.Dispose();
            _connection.Dispose();
        }
© www.soinside.com 2019 - 2024. All rights reserved.