我正在构建Windows服务,我的目标是当队列中显示消息时,它将侦听RabbitMQ队列并向Windows事件日志写出日志。我试图弄清楚如何触发服务并在RabbitMQ队列中看到消息时立即写日志。这是我的Windows服务代码:
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.Diagnostics;
using System.ServiceProcess;
using System.Text;
namespace RabbitMQService
{
public partial class RabbitMQService : ServiceBase
{
private int eventId = 1;
public RabbitMQService()
{
InitializeComponent();
eventLog1 = new System.Diagnostics.EventLog();
if (!System.Diagnostics.EventLog.SourceExists("MySource"))
{
System.Diagnostics.EventLog.CreateEventSource(
"MySource", "MyNewLog");
}
eventLog1.Source = "MySource";
eventLog1.Log = "MyNewLog";
}
protected override void OnStart(string[] args)
{
eventLog1.WriteEntry("In OnStart");
System.Timers.Timer timer = new System.Timers.Timer();
timer.Interval = 60000; // 60 seconds
timer.Elapsed += new System.Timers.ElapsedEventHandler(this.OnTimer);
timer.Start();
}
public void OnTimer(object sender, System.Timers.ElapsedEventArgs args)
{
GetMessage();
eventLog1.WriteEntry("Monitoring the System", EventLogEntryType.Information, eventId++);
}
public void GetMessage()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) =>
{
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
eventLog1.WriteEntry("Message Received: " + message);
};
channel.BasicConsume(queue: "hello",
autoAck: true,
consumer: consumer);
eventLog1.WriteEntry("Starting to listen for messages from the queue");
}
}
protected override void OnStop()
{
eventLog1.WriteEntry("In OnStop.");
}
protected override void OnContinue()
{
eventLog1.WriteEntry("In OnContinue.");
}
}
}
现在,仅当timer方法每60秒触发一次时,它才将消息写入日志。当我将该实验构建为控制台应用程序时,客户端发送消息后,一旦消息到达队列,它将立即显示消息。仅供参考,这是发送消息的客户端控制台应用程序:
using System;
using System.Text;
using RabbitMQ.Client;
namespace Send
{
class Send
{
static void Main(string[] args)
{
var factory = new ConnectionFactory() { HostName = "xxx.xxx.xxx.xxx", UserName = "xxx", Password = "xxx" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "hello",
durable: false,
exclusive: false,
autoDelete: false,
arguments: null);
string message = "Hello World!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish(exchange: "",
routingKey: "hello",
basicProperties: null,
body: body);
Console.WriteLine(" [x] Sent {0}", message);
}
Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
}
}
}
我上面提到的接收控制台应用程序与我构建的Windows服务的GetMessage()方法中的代码完全一样。