Fork me on GitHub
NET 使用 RabbitMQ

NET 使用 RabbitMQ

前言

最近项目要使用RabbitMQ,园里里面已经有很多优秀的文章,Rabbitmq官网也有.net实例。这里我尝试下图文并茂之形式记录下使用的过程。

安装

RabbitMQ是建立在erlang OTP平台下,因此在windows下需要下载并安装以下两个组件:

1. Erlang OTP For windows

2. Rabbit MQ Windows Service Install

RabbitMQ一般还需要安装其基于http的管理平台插件,这个平台插件便于我们查看和管理RabbitMQ,可以通过命令行将其启用:

rabbitmq-plugins enable rabbitmq_management

之后就可以通过 http://localhost:15672/ 登录,账号的密码和密码可以使用默认的guest/guest,登录之后的页面:

RabbitMq 使用

下图就是具体的使用流程

其方框中就是Rabbitmq的message broker,我们将上图按上下方式来解释:

1. 信息发送端将消息(message)发送到exchange

2. exchange接受消息之后,负责将其路由到具体的队列中

3. Bindings负责连接exchange和队列(queue)

4. 消息到达队列(queue),然后等待被消息接收端处理

5. 消息接收端处理消息

初始化RabbitMQ

现在我们用代码来demo流程,首先在nuget上获取RabbitMQ.Client:

然后创建图中2,3,4步需要的exchange,bingding,queue

复制代码
string exchangeName = "test.exchange";
string queueName = "test1.queue";
string otherQueueName = "test2.queue";
using (IConnection conn = rabbitMqFactory.CreateConnection())
using (IModel channel = conn.CreateModel())
{
    //2 定义一个exchange
    channel.ExchangeDeclare(exchangeName, "direct", durable: true, autoDelete: false, arguments: null);

    //4 定义两个queue
    channel.QueueDeclare(queueName, durable: true, exclusive: false, autoDelete: false, arguments: null);
    channel.QueueDeclare(otherQueueName, durable: true, exclusive: false, autoDelete: false, arguments: null);

    //3 定义exchange到queue的binding
    channel.QueueBind(queueName, exchangeName, routingKey: queueName);
    channel.QueueBind(otherQueueName, exchangeName, routingKey: otherQueueName);
}
复制代码

创建成功之后可以在rabbit的管理平台查看:

发送消息

从图上我们得知消息是发送到rabbitmq的exchange,但可以传一些消息属性如routingkey,一下代码中我们将队列的名字作为routingkey传进去:

复制代码
string exchangeName = "test.exchange";
string queueName = "test1.queue";
string otherQueueName = "test2.queue";
using (IConnection conn = rabbitMqFactory.CreateConnection())
using (IModel channel = conn.CreateModel())
{
    var props = channel.CreateBasicProperties();
    props.Persistent = true;

    var msgBody = Encoding.UTF8.GetBytes("Hello, World!");

    //1. 发送消息到exchange ,但加上routingkey
    channel.BasicPublish(exchangeName, routingKey: queueName, basicProperties: props, body: msgBody);
    channel.BasicPublish(exchangeName, routingKey: otherQueueName, basicProperties: props, body: msgBody);
}
复制代码

发送之后可以在rabbitmq上看到:

 

接收消息

复制代码
string queueName = "test1.queue";
string otherQueueName = "test2.queue";
using (IConnection conn = rabbitMqFactory.CreateConnection())
using (IModel channel = conn.CreateModel())
{
    //5. 从test1.queue 队列获取消息
    BasicGetResult msgResponse = channel.BasicGet(queueName, noAck: true);
    string msgBody = Encoding.UTF8.GetString(msgResponse.Body);

    //5. 从test2.queue 队列获取消息
    msgResponse = channel.BasicGet(otherQueueName, noAck: true);
    msgBody = Encoding.UTF8.GetString(msgResponse.Body);

}
复制代码

 总结

通过以上的简述我们对rabbitmq的使用就有了大概的了解。

 
 
标签: RabbitMQ
posted on 2017-01-08 21:46  HackerVirus  阅读(380)  评论(0编辑  收藏  举报