【发布时间】:2016-11-26 04:11:46
【问题描述】:
我正在完成我使用 RabbitMQ 的第一步,并且想知道为什么这不起作用。
基础教程 (https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html) 有一个可执行文件发送给代理,另一个可执行文件接收。
我通过 Visual Studio 中的单个控制台应用程序运行此代码,但收不到任何消息。
如果我将“接收”代码放入单独的控制台应用程序并打开它,我会收到消息(没有其他代码更改)。
有人可以解释为什么我不能在同一个过程中同时拥有两者吗?我想连接工厂会相应地处理独立的连接,不管它是否是同一个过程。
为了完整起见(尽管我怀疑它是必需的),以下代码在我取出“接收器”代码并将其放入它自己的控制台应用程序之前不起作用:
class Program
{
static void Main(string[] args) {
Receiver.Receive();
Console.WriteLine("receiver set up");
System.Threading.Thread.Sleep(5000);
Console.WriteLine("sending...");
Test.Send();
// can also reverse order of send/receive methods, same result
Console.ReadKey();
}
}
public class Receiver
{
public static void Receive() {
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection()) {
using (var channel = connection.CreateModel()) {
channel.QueueDeclare("hello", false, false, false, null);
var consumer = new EventingBasicConsumer(channel);
consumer.Received += (model, ea) => {
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
System.Diagnostics.Debug.WriteLine("=====================");
System.Diagnostics.Debug.WriteLine(message);
System.Diagnostics.Debug.WriteLine("=====================");
};
channel.BasicConsume("hello", true, consumer);
}
}
}
}
public class Test
{
public static void Send() {
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection()) {
using (var channel = connection.CreateModel()) {
channel.QueueDeclare("hello", false, false, false, null);
string message = "Check it!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish("", "hello", null, body);
}
}
}
}
【问题讨论】: