2016-11-25 68 views
2

我正在通過我的第一步與RabbitMQ工作,並有一個問題,爲什麼這不起作用。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); 

      } 
     } 

    } 

} 

回答

1

我覺得代碼有問題。當你發送消息時,接收連接和通道已經死了(Dispose called)。從現場的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都還活着,當客戶端接收的消息。

+0

你是對的......我的Console.ReadKey線在接收器的使用塊之外,這實際上意味着我沒有保持連接打開(讓它在它有機會接收之前進行處理)。我以前的評論道歉對你的建議提出質疑。謝謝! – jleach

+0

@ jdl134679我很樂意幫助你=)線程是陰險的! –

相關問題