我是RabbitMQ的新手,我很难找到一个VS2017 C#示例,该示例可以打印到控制台。我可以发送和接收消息没问题,但我想获取消息的内容并实际使用它。以下是我的代码:
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System.IO;
namespace MyCode
{
class Program
{
public static void Main()
{
var factory = new ConnectionFactory() { HostName = "xxx.xx.x.x", UserName = "MyTest", Password = "MyTest", Port = 5672 };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "MyTest", 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);
DoSomething(message);
};
channel.BasicConsume(queue: "MyTest", autoAck: true, consumer: consumer);
}
}
}
static void DoSomething(string message)
{
File.AppendAllText(@"C:\RMQ.txt", message);
}
}
}
问题是,我似乎无法从Consumer.Received步骤中获得任何东西。任何帮助将不胜感激!
EDIT ::
我能够通过使用此代码使其工作:
var factory = new ConnectionFactory() { HostName = "xxx.xx.x.x", UserName = "MyTest", Password = "MyTest", Port = 5672 };
using (IConnection connection = factory.CreateConnection())
{
using (IModel channel = connection.CreateModel())
{
channel.QueueDeclare(queue: "MyTest", durable: false, exclusive: false, autoDelete: false, arguments: null);
BasicGetResult consumer = channel.BasicGet("MyTest", true);
if (consumer != null)
{
string message = Encoding.UTF8.GetString(consumer.Body);
DoSomething(message);
}
}
}
有人看到有任何问题吗?
答案 0 :(得分:1)
第一段代码的问题在于程序在处理任何消息之前完成执行。 EventingBasedConsumer
是异步的,并且实际上不会阻止您的程序退出。您需要实现某种等待以便能够实际处理消息。尝试在Thread.Sleep(10000);
之后添加Channel.BasicConsume
并检查是否有任何消息正在处理中。