我正在学习 RabbitMQ 教程(这个)并遇到了问题。
如果我按照教程中提供的方式编写代码 - 它可以正常工作。但我想将逻辑移动到单独的类中,这样它看起来更好并且可以重用。
public class Consumer
{
private ConnectionFactory factory;
private List<string> receivedData;
public Consumer()
{
receivedData = new List<string>();
factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("hello", false, false, false, null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
receivedData.Add(message);
};
channel.BasicConsume("hello", true, consumer);
}
}
public List<string> GetAllReceivedMessages()
{
return receivedData;
}
}
主要程序
var consumer = new Consumer();
while (true)
{
Console.Clear();
var messages = consumer.GetAllReceivedMessages();
foreach (var msg in messages)
{
Console.WriteLine(msg);
}
Thread.Sleep(5000);
}
我没有发现与原版有任何差异。但receivedData列表一直是空的。为什么?
提前致谢。
当您的
using
语句退出时,通道和连接将关闭。