我有一个简单的RabbitMQ使用者,但我相信他正在跳过Received事件。
逐行调试时,它会读取它们,打印它们并执行跟随它的所有逻辑。但是当我在没有调试的情况下运行它时,它不是。
我确保队列中有消息:
消费代码:
namespace AutoMatcher.QueuesImpl
{
public class RabbitMQImpl : IQueue
{
// 1. Message Received Event -- returns message
// 2. private RabbitMq object implementation
// 3. under interfaces -- add new interfaces for queues that implements start listening and this event
// 4. Installer object -- Registers private object as public interface in container
private readonly IBotFactory _factory;
public RabbitMQImpl(IBotFactory factory)
{
_factory = factory;
}
public void StartListening()
{
var factory = new ConnectionFactory()
{
HostName = "localhost",
Port = 5672
};
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
//await Task.Yield();
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
var jsonMessage = JsonConvert.DeserializeObject<MessageWithoutUser>(message);
IBot bot = _factory.GetBot(jsonMessage);
bot.Execute(jsonMessage.MessageId, jsonMessage.UserId, jsonMessage.Likes, jsonMessage.Service, jsonMessage.Time);
};
channel.BasicConsume(queue: "messages",
autoAck: true,
consumer: consumer);
}
}
}
}
}
我真的不知道发生了什么,有什么建议吗?谢谢。
在班级建设者面前致电。
var factory = new ConnectionFactory()
{ HostName = "localhost",
Port = 5672
};
首先创建工厂,然后分配给_factory。
如注释中所述,下面的代码部分是有问题的,因为在离开using语句之后,连接已关闭,因此从未收到任何消息。
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
....
}
}
相反,您可以将连接和通道都保存为属性。
public class RabbitMQImpl : IQueue
{
private Connection _connection;
private Channel _channel;
private readonly IBotFactory _factory;
public RabbitMQImpl(IBotFactory factory)
{
_factory = factory;
}
public void StartListening()
{
var factory = new ConnectionFactory()
{
HostName = "localhost",
Port = 5672
};
_connection = factory.CreateConnection();
_channel = connection.CreateModel();
// your code
}
}
您可以在类IDisposable
中实现RabbitMQImpl
接口以关闭连接和通道,但是要记住,可以快速创建“反模式”,请参见此comment
我希望这会有所帮助。