.NET 6 控制台应用程序,RabbitMQ 在脱离 Program.cs 文件时无法工作

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

我正在尝试根据此示例在控制台应用程序应用程序上创建一个消费者:
https://rabbitmq-website.pages.dev/tutorials/tutorial-six-dotnet

我注意到当我将program.cs文件外部的代码转移到不同的类时,它不起作用,代码完全相同

我的program.cs文件中的代码

var factory = new ConnectionFactory { HostName = "localhost" };
using var connection = factory.CreateConnection();
using var channel = connection.CreateModel();

channel.QueueDeclare(queue: "rpc_queue",
                     durable: false,
                     exclusive: false,
                     autoDelete: false,
                     arguments: null);
channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false);
var consumer = new EventingBasicConsumer(channel);
channel.BasicConsume(queue: "rpc_queue",
                     autoAck: false,
                     consumer: consumer);

consumer.Received += (model, ea) =>
{
    string response = string.Empty;

    var body = ea.Body.ToArray();
    var props = ea.BasicProperties;
    var replyProps = channel.CreateBasicProperties();
    replyProps.CorrelationId = props.CorrelationId;

    try
    {
        var message = Encoding.UTF8.GetString(body);
        Console.WriteLine($"Consumer: message from clien => {message}");
        response = "This message is from Consumer";
    }
    catch (Exception ex)
    {
        response = string.Empty;
    }
    finally
    {
        var responseBytes = Encoding.UTF8.GetBytes(response);
        channel.BasicPublish(exchange: string.Empty,
                             routingKey: props.ReplyTo,
                             basicProperties: replyProps,
                             body: responseBytes);
        channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false);
    }
};
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();

其他一些类中的代码是完全相同的

public class RcpServer
{
 public void Start()
 {
  [Same code as above without the 2 last lines (Console.read/Console.write)]
 }
}

然后在program.cs文件中我有以下代码

RcpServer rcpServer = new RcpServer();
rcpServer.Start();
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();

但是这段代码不起作用,

经过一番搜索,我发现了这篇文章 RABBITMQ C# 在控制台上运行良好,但不适用于服务,但不幸的是无法解决它:(

我需要的是将消费者作为“后台”服务运行。
请帮忙,
预先感谢。

c# .net rabbitmq
1个回答
0
投票

您可以使用.net辅助服务来消费消息参见

© www.soinside.com 2019 - 2024. All rights reserved.