2. Sending
第一个program send.cs:发送Hello world 到queue。正如我们在上篇文章提到的,你程序的第9行就是建立连接,第12行就是创建channel,第14行创建名字为hello的queue。
1 using System; 2 using RabbitMQ.Client; 3 using System.Text; 4 5 class Send 6 { 7 public static void Main() 8 { 9 var factory = new ConnectionFactory() { HostName = "localhost" }; 10 using (var connection = factory.CreateConnection()) 11 { 12 using (var channel = connection.CreateModel()) 13 { 14 channel.QueueDeclare("hello", false, false, false, null); 15 string message = "Hello World!"; 16 var body = Encoding.UTF8.GetBytes(message); 17 channel.BasicPublish("", "hello", null, body); 18 Console.WriteLine(" [x] Sent {0}", message); 19 } 20 } 21 } 22 }
从架构图可以看出,Producer只能发送到exchange,它是不能直接发送到queue的。
第17行:现在我们使用默认的exchange(名字是空字符)。这个默认的exchange允许我们发送给指定的queue。routing_key就是指定的queue名字。
3. Receiving
第二个program receive.cs 将从queue中获取Message并且打印到屏幕。
1 using RabbitMQ.Client; 2 using RabbitMQ.Client.Events; 3 using System; 4 using System.Text; 5 6 class Receive 7 { 8 public static void Main() 9 { 10 var factory = new ConnectionFactory() { HostName = "localhost" }; 11 using (var connection = factory.CreateConnection()) 12 { 13 using (var channel = connection.CreateModel()) 14 { 15 channel.QueueDeclare("hello", false, false, false, null); 16 var consumer = new QueueingBasicConsumer(channel); 17 channel.BasicConsume("hello", true, consumer); 18 Console.WriteLine(" [*] Waiting for messages." + "To exit press CTRL+C"); 19 while (true) 20 { 21 var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();//阻塞 22 var body = ea.Body; 23 var message = Encoding.UTF8.GetString(body); 24 Console.WriteLine(" [x] Received {0}", message); 25 } 26 } 27 } 28 } 29 }
4. 最终运行
先运行 send.cs ,send.cs 每次运行完都会停止。注意:现在数据已经存到queue里了。在接收它receive.cs.
转:
http://www.rabbitmq.com/tutorials/tutorial-one-dotnet.html(官网)
http://blog.csdn.net/anzhsoft/article/details/19570187(翻译)
时间: 2024-10-02 09:44:11