我正在尝试实现一个WinForm RabbitMQ客户端,我从服务器接收消息如下 -
private void Form1_Load(object sender, System.EventArgs e)
{
backgroundWorker1.RunWorkerAsync();
}
private void backgroundWorker1_DoWork(object sender, DoWorkEventArgs e)
{
var factory = new ConnectionFactory() { HostName = "192.168.100.6", Password = "pass", UserName = "username" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("CallCenter", false, false, false, null);
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume("CallCenter", true, consumer);
while (true)
{
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
MessageBox.Show(message);
}
}
}
}
private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
if (backgroundWorker1.IsBusy)
{
backgroundWorker1.CancelAsync();
}
backgroundWorker1.Dispose();
}
我很确定这不是一个好方法。相反,如果有OnMessageReceived
事件会更好。
您对RabbiMQ中基于事件的消息接收有什么好的例子吗?
答案 0 :(得分:1)
你这样做的方式是正确的。 consumer.Queue.Dequeue();
本质上是一个OnMessageReceived,它是一个阻塞调用,它等待从兔子发送消息。