I'm trying to create a consumer on console application app according to this example:
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# Works nice on console but not for a service个,但不幸的是没有解决:
What I need is to run the consumer as "background" service.
Please help,
Thanks in advance.