gpt4 book ai didi

c# - RabbitMQ 无法从同一进程发送和接收

转载 作者:太空宇宙 更新时间:2023-11-03 12:36:26 26 4
gpt4 key购买 nike

我正在使用 RabbitMQ 完成我的第一步,我有一个问题,为什么这不起作用。

基础教程 ( https://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html ) 有一个可执行文件发送给代理,另一个可执行文件接收它。

我通过 Visual Studio 中的单个控制台应用程序运行此代码,但无法收到任何消息。

如果我将“接收”代码放入一个单独的控制台应用程序并打开它,我会收到消息(没有其他代码更改)。

有人可以解释为什么我不能在同一个过程中同时拥有两者吗?我以为连接工厂会相应地处理独立的连接,不管它是否是同一个进程。


为了完整起见(虽然我怀疑它是必需的),这里的代码在我取出“Receiver”代码并将其放入它自己的控制台应用程序之前不起作用:

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);

}
}

}

}

最佳答案

我认为代码有问题。当您发送消息时,接收连接和 channel 已经失效(调用 Dispose)。

来自 RabbitMQ 站点的标准代码:

    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);
Console.WriteLine(" [x] Received {0}", message);
};
channel.BasicConsume(queue: "hello",
noAck: true,
consumer: consumer);

Console.WriteLine(" Press [enter] to exit.");
Console.ReadLine();
}
当客户端收到消息时,

connectionchannel 还处于事件状态。

关于c# - RabbitMQ 无法从同一进程发送和接收,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40811365/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com