下面的程序基本上是來自C#Rabbit MQ教程中的Receiver/Worker程序的程序:https://www.rabbitmq.com/tutorials/tutorial-two-dotnet.html(添加了計數器)。RabbitMQ BasicConsume和事件驅動的與Console.ReadLine()相關的問題
有跡象表明,已經難倒我關於它的兩三件事:
1)如果我註釋掉「到Console.ReadLine()」它消耗從隊列中的消息,並顯示:
Start Press [enter] to exit. My End - CountMessagesProcessed=0
我測試的前幾次,我無法弄清楚發生了什麼事。
2)該行從不在輸出中顯示:Console.WriteLine(「按[enter]退出。」);.大概是因爲它在「Console.ReadLine();」之前,但是爲什麼? ReadLine事件和BasicConsumer之間的相互作用是什麼?
3)MQ教程頁面聲稱使用CNTL-C來停止「偵聽器」進程,但是我發現只要按下回車鍵就可以很好地工作。
我以前用線程編寫過MQSeries的監聽器,我可能會更喜歡它,但只是想了解提供的基本教程。
using System;
using System.Collections.Generic;
using System.Text;
using System.Threading.Tasks;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
namespace RabbitMQReceiver
{
class Receive
{
public static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "localhost" };
var myQueuename = "MyQueueName1";
Console.WriteLine("My Start");
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: myQueuename,
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
int countMessagesProcessed = 0;
// this chunk of code is passed as parm/variable to BasicConsume Method below to process each item pulled of the Queue
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
countMessagesProcessed++;
Console.WriteLine(" [x] Received {0}", message);
}
channel.BasicConsume(queue: myQueuename,
noAck: true,
consumer: consumer);
Console.WriteLine(" Press [enter] to exit."); // this line never shows up in output
Console.ReadLine(); // if this line is commented out the message are consumed, but no Console.WriteLines appear at all.
Console.WriteLine("My End - CountMessagesProcessed=" + countMessagesProcessed);
}
}
}
}