首页 技术 正文
技术 2022年11月20日
0 收藏 958 点赞 2,941 浏览 1796 个字

2. Sending

RabbitMQ消息队列(二):"Hello, World"[转]

第一个program send.cs:发送Hello world 到queue。正如我们在上篇文章提到的,你程序的第9行就是建立连接,第12行就是创建channel,第14行创建名字为hello的queue。

 using System;
using RabbitMQ.Client;
using System.Text; class Send
{
public static void Main()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("hello", false, false, false, null);//hello是queue的名字
string message = "Hello World!";
var body = Encoding.UTF8.GetBytes(message);
channel.BasicPublish("", "hello", null, body);//hello是routing key的名字
Console.WriteLine(" [x] Sent {0}", message);
}
}
}
}

从架构图可以看出,Producer只能发送到exchange,它是不能直接发送到queue的。

第17行:现在我们使用默认的exchange(名字是空字符)。这个默认的exchange允许我们发送给指定的queue。routing_key就是指定的queue名字。

3. Receiving

RabbitMQ消息队列(二):"Hello, World"[转]

第二个program receive.cs 将从queue中获取Message并且打印到屏幕。

 using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text; class Receive
{
public static void Main()
{
var factory = new ConnectionFactory() { HostName = "localhost" };
using (var connection = factory.CreateConnection())
{
using (var channel = connection.CreateModel())
{
channel.QueueDeclare("hello", false, false, false, null);//hello是queue的名字
var consumer = new QueueingBasicConsumer(channel);
channel.BasicConsume("hello", true, consumer);//hello是queue的名字,这里可以理解为hello是routing key的名字。因为这个例子没有使用指定名称的exchange(实际上使用的是默认的exchange名字),所以queue的名字和routing key的名字是相同的。在第五篇文章中介绍如果使用了指定名称的exchange,queue name和routing key的关系与用法。
Console.WriteLine(" [*] Waiting for messages." + "To exit press CTRL+C");
while (true)
{
var ea = (BasicDeliverEventArgs)consumer.Queue.Dequeue();//阻塞
var body = ea.Body;
var message = Encoding.UTF8.GetString(body);
Console.WriteLine(" [x] Received {0}", message);
}
}
}
}
}

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(翻译)

相关推荐
python开发_常用的python模块及安装方法
adodb:我们领导推荐的数据库连接组件bsddb3:BerkeleyDB的连接组件Cheetah-1.0:我比较喜欢这个版本的cheeta…
日期:2022-11-24 点赞:878 阅读:8,954
Educational Codeforces Round 11 C. Hard Process 二分
C. Hard Process题目连接:http://www.codeforces.com/contest/660/problem/CDes…
日期:2022-11-24 点赞:807 阅读:5,479
下载Ubuntn 17.04 内核源代码
zengkefu@server1:/usr/src$ uname -aLinux server1 4.10.0-19-generic #21…
日期:2022-11-24 点赞:569 阅读:6,291
可用Active Desktop Calendar V7.86 注册码序列号
可用Active Desktop Calendar V7.86 注册码序列号Name: www.greendown.cn Code: &nb…
日期:2022-11-24 点赞:733 阅读:6,108
Android调用系统相机、自定义相机、处理大图片
Android调用系统相机和自定义相机实例本博文主要是介绍了android上使用相机进行拍照并显示的两种方式,并且由于涉及到要把拍到的照片显…
日期:2022-11-24 点赞:512 阅读:7,740
Struts的使用
一、Struts2的获取  Struts的官方网站为:http://struts.apache.org/  下载完Struts2的jar包,…
日期:2022-11-24 点赞:671 阅读:4,774