From: http://lostechies.com/derekgreer/2012/04/02/rabbitmq-for-windows-direct-exchanges/

RabbitMQ for Windows: Direct Exchanges

Posted by Derek Greer on April 2, 2012

This is the fifth installment to the series: RabbitMQ for Windows.  In thelast installment, we took a look at the four exchange types provided by RabbitMQ: Direct, Fanout, Topic, and Headers.  In this installment we’ll walk through an example which uses a direct exchange type directly and we’ll take a look at the push API.

In the Hello World example from the second installment of the series, we used a direct exchange type implicitly by taking advantage of the automatic  binding of queues to the default exchange using the queue name as the routing key.  The example we’ll work through this time will be similar, but we’ll declare and bind to the exchange explicitly.

This time our example will be a distributed logging application.  We’ll create a Producer console application which publishes a logging message for some noteworthy action and a Consumer console application which displays the message to the console.

PunCha:作者之前的5个帖子,很简单,看的我是行云流水~,可是看到这个帖子,让我一头雾水从而研究了2个小时,这才有了RabbitMQ学习篇一。我并不觉得这篇文章的例子是个好例子!作者的意图很明显,因为DirectExchange太简单了,没有深度,所以他参差了一个BasicConsumer函数(Block调用),但是却把简单问题复杂化了。而且混淆了一些概念,我这里作一下说明:

1. Exchange只用于Producer,RoutingKey用来绑定Exchange和Queue,这个一般在Producer这端做的,但是作者却放到了Consumer这端。可以是可以,但是作者应该加一个说明。

2. 作者这个用法说明了一个问题,假如Producer把消息发到没有绑定Queue的Exchange消息会丢失!

3. 作者让我对RMQ有了深刻的了解,嘿嘿。

Beginning with our Producer app, we’ll start by establishing a connection using the default settings, create the connection, and create a channel:

using RabbitMQ.Client;

namespace Producer
{
  class Program
  {
    static void Main(string[] args)
    {
      var connectionFactory = new ConnectionFactory();
      IConnection connection = connectionFactory.CreateConnection();
      IModel channel = connection.CreateModel();
    }
  }
}

Next, we need to declare the exchange we’ll be publishing our message to.  We need to give our exchange a name in order to reference it later, so let’s use “direct-exchange-example”:

channel.ExchangeDeclare("direct-exchange-example", ExchangeType.Direct);

The second parameter indicates the exchange type.  For the official RabbitMQ .Net client, this is just a simple string containing one of the values: direct, fanout, topic, or headers.  The type RabbitMQ.Client.ExchangeType defines each of the exchange types as a constant for convenience. [PunCha:这里为什么不用一个枚举型?没搞懂为什么要这样设计]

Next, let’s call some method which might produce a value worthy of interest.  We’ll call the method DoSomethingInteresting() and have it return a string value:

string value = DoSomethingInteresting();

For the return value, the implementation of DoSomethingInteresting() can just return the string value of a new Guid:

static string DoSomethingInteresting()
{
  return Guid.NewGuid().ToString();
}

Next, let’s use the returned value to create a log message containing a severity level of Information:

string logMessage = string.Format("{0}: {1}", TraceEventType.Information, value);

Next, we need to convert our log message to a byte array and publish the message to our new exchange:

byte[] message = Encoding.UTF8.GetBytes(logMessage); channel.BasicPublish("direct-exchange-example", "", null, message);

Here, we use an empty string as our routing key [PunCha: 所以,假如想成功发送消息,必然有一个名叫direct-exchange-example的Exchange对象和一个空的RoutingKey用来绑定某个Queue。In this case,是在Consumer这端实现的,这也是为什么Consumer一定要先运行的原因。] and null for our message properties.

We end our Producer by closing the channel and connection:

channel.Close();
connection.Close();

Here’s the full listing:

using System;
using System.Diagnostics;
using System.Text;
using System.Threading;
using RabbitMQ.Client; namespace Producer
{
  class Program
  {
    static void Main(string[] args)
    {
      Thread.Sleep(1000);
      var connectionFactory = new ConnectionFactory();
      IConnection connection = connectionFactory.CreateConnection();
      IModel channel = connection.CreateModel();       channel.ExchangeDeclare("direct-exchange-example", ExchangeType.Direct);
      string value = DoSomethingInteresting();
      string logMessage = string.Format("{0}: {1}", TraceEventType.Information, value);       byte[] message = Encoding.UTF8.GetBytes(logMessage);
      channel.BasicPublish("direct-exchange-example", "", null, message);       channel.Close();
      connection.Close();
    }     static string DoSomethingInteresting()
    {
      return Guid.NewGuid().ToString();
    }
  }
}

Note that our logging example’s Producer differs from our Hello World’s Producer in that we didn’t declare a queue this time.[PunCha: 特别注意,我们没有声明Queue! 这个不同于HelloWorld。]  In our Hello World example, we needed to run our Producer before the Consumer since the Consumer simply retrieved a single message and exited.  Had we published to the default exchange without declaring the queue first, our message would simply have been discarded by the server before the Consumer had an opportunity to declare and bind the queue.

Next, we’ll create our Consumer which starts the same way as our Producer code:

using RabbitMQ.Client;

namespace Consumer
{
  class Program
  {
    static void Main(string[] args)
    {
      var connectionFactory = new ConnectionFactory();
      IConnection connection = connectionFactory.CreateConnection();
      IModel channel = connection.CreateModel();       channel.ExchangeDeclare("direct-exchange-example", ExchangeType.Direct);
    }
  }
}

Next, we need to declare a queue to bind to our exchange.  Let’s name our queue “logs”:

 
channel.QueueDeclare("logs", false, false, true, null);

To associate our logs queue with our exchange, we use the QueueBind() method providing the name of the queue, the name of the exchange, and the binding key to filter messages on: [PunCha:这里就产生了一个绑定,Exchange是direct-exchange-example,Queue是logs,纽带是空的RoutingKey。这个与Producer代码相匹配。]

channel.QueueBind("logs", "direct-exchange-example", "");

At this point we could consume messages using the pull API method BasicGet() as we did in the Hello World example, but this time we’ll use the push API.  To have messages pushed to us rather than us pulling messages, we first need to declare a consumer:

var consumer = new QueueingBasicConsumer(channel);

To start pushing messages to our consumer, we call the channel’s BasicConsume() method and tell it which consumer to start pushing messages to: [PunCha:注意,取数据永远只需要Queue,没有Exchange和RoutingKey。]

channel.BasicConsume(“logs”, true, consumer);

Here, we specify the queue to consume messages from, a boolean flag instructing messages to be auto-acknowledged (see discussion in the Getting the Message section of Hello World Review), and the consumer to push the messages to.

Now, any messages placed on the queue will automatically be retrieved and placed in a local in-memory queue.  To dequeue a message from the local queue, we call the Dequeue() method on the consumer’s Queue property:

var eventArgs = (BasicDeliverEventArgs)consumer.Queue.Dequeue();

This method call blocks until a message is available to be dequeued, or until an EndOfStreamException is thrown indicating that the consumer was cancelled, the channel was closed, or the connection otherwise was terminated.[PunCha:说实话,我的感觉,无论是返回参数(需要强转),还是这个函数的取名,都很奇怪。。Dequeue的时候Block。。。]

Once the Dequeue() method returns, the BasicDeliverEventArgs contains the bytes published from the Producer in the Body property, so we can convert this value back into a string and print it to the console:

var message = Encoding.UTF8.GetString(eventArgs.Body);
Console.WriteLine(message);

We end our Consumer by closing the channel and connection:

channel.Close();
connection.Close();

Here’s the full listing:

using System;
using System.Text;
using RabbitMQ.Client;
using RabbitMQ.Client.Events; namespace Consumer
{
  class Program
  {
    static void Main(string[] args)
    {
      var connectionFactory = new ConnectionFactory();
      IConnection connection = connectionFactory.CreateConnection();
      IModel channel = connection.CreateModel();       channel.ExchangeDeclare("direct-exchange-example", ExchangeType.Direct);
      channel.QueueDeclare("logs", false, false, true, null);
      channel.QueueBind("logs", "direct-exchange-example", "");       var consumer = new QueueingBasicConsumer(channel);
      channel.BasicConsume("logs", true, consumer);       var eventArgs = (BasicDeliverEventArgs) consumer.Queue.Dequeue();       string message = Encoding.UTF8.GetString(eventArgs.Body);
      Console.WriteLine(message);       channel.Close();
      connection.Close();
      Console.ReadLine();
    }
  }
}

If we run the resulting Consumer.exe at this point, it will block until a message is routed to the queue.  Running the Producer.exe from another shell produces a message on the consumer console similar to the following:

Information: 610fe447-bf31-41d2-ae29-414b2d00087b
Note: For a convenient way to execute both the Consumer and Producer from within Visual Studio, go to the solution properties and choose “Set StartUp Projects …”.  Select the “Multiple startup projects:”[PunCha:这个功能蛮好的,我以前竟然不知道~] option and set both the Consumer and Producer to the Action: Start.  Use the arrows to the right of the projects to ensure the Consumer is started before the Producer.  In some cases, this can still result in the Producer publishing the message before the Consumer has time to declare and bind the queue, so putting a Thread.Sleep(1000) at the start of your Producer should ensure things happen in the required order.  After this, you can run your examples by using Ctrl+F5 (which automatically prompts to exit).

That concludes our direct exchange example.  Next time, we’ll take a look at the Fanout exchange type.

http://blog.csdn.net/puncha/article/details/8449395

RabbitMQ学习之:(六)Direct Exchange (转贴+我的评论)的更多相关文章

  1. rabbitmq学习(六) —— 主题

    主题交换(Topic exchange) 使用 topic 类型的交换器,不能有任意的绑定键,它必须是由点隔开的一系列的标识符组成.标识符可以是任何东西,但通常它们指定与消息相关联的一些功能.其中,有 ...

  2. RabbitMQ学习笔记六:RabbitMQ之消息确认

    使用消息队列,必须要考虑的问题就是生产者消息发送失败和消费者消息处理失败,这两种情况怎么处理. 生产者发送消息,成功,则确认消息发送成功;失败,则返回消息发送失败信息,再做处理. 消费者处理消息,成功 ...

  3. rabbitMQ学习(六)

    请求模式 客户端: import com.rabbitmq.client.ConnectionFactory; import com.rabbitmq.client.Connection; impor ...

  4. rabbitMQ学习笔记(六) topic类型消息。

    上一节中使用了消息路由,消费者可以选择性的接收消息. 但是这样还是不够灵活. 比如某个消费者要订阅娱乐新闻消息 . 包括新浪.网易.腾讯的娱乐新闻.那么消费者就需要绑定三次,分别绑定这三个网站的消息类 ...

  5. RabbitMQ学习总结 第六篇:Topic类型的exchange

    目录 RabbitMQ学习总结 第一篇:理论篇 RabbitMQ学习总结 第二篇:快速入门HelloWorld RabbitMQ学习总结 第三篇:工作队列Work Queue RabbitMQ学习总结 ...

  6. RabbitMQ学习系列(四): 几种Exchange 模式

    上一篇,讲了RabbitMQ的具体用法,可以看看这篇文章:RabbitMQ学习系列(三): C# 如何使用 RabbitMQ.今天说些理论的东西,Exchange 的几种模式. AMQP协议中的核心思 ...

  7. Redis总结(五)缓存雪崩和缓存穿透等问题 Web API系列(三)统一异常处理 C#总结(一)AutoResetEvent的使用介绍(用AutoResetEvent实现同步) C#总结(二)事件Event 介绍总结 C#总结(三)DataGridView增加全选列 Web API系列(二)接口安全和参数校验 RabbitMQ学习系列(六): RabbitMQ 高可用集群

    Redis总结(五)缓存雪崩和缓存穿透等问题   前面讲过一些redis 缓存的使用和数据持久化.感兴趣的朋友可以看看之前的文章,http://www.cnblogs.com/zhangweizhon ...

  8. PHP 下基于 php-amqp 扩展的 RabbitMQ 简单用例 (一) -- 安装 AMQP 扩展和 Direct Exchange 模式

    Windows 安装 amqp 扩展 RabbitMQ 是基于 amqp(高级消息队列协议) 协议的.使用 RabbitMQ 前必须为 PHP 安装相应的 amqp 扩展. 下载相应版本的 amqp ...

  9. RabbitMQ指南之四:路由(Routing)和直连交换机(Direct Exchange)

    在上一章中,我们构建了一个简单的日志系统,我们可以把消息广播给很多的消费者.在本章中我们将增加一个特性:我们可以订阅这些信息中的一些信息.例如,我们希望只将error级别的错误存储到硬盘中,同时可以将 ...

随机推荐

  1. Bootstrap treegrid 实现树形表格结构

    前言 :最近的项目中需要实现树形表格功能,由于前端框架用的是bootstrap,但是bootstrapTable没有这个功能所以就找了一个前端的treegrid第三方组件进行了封装.现在把这个封装的组 ...

  2. Flutter——Container组件(容器组件)

    名称 功能 alignment topCenter:顶部居中对齐 topLeft:顶部左对齐 topRight:顶部右对齐 center:水平垂直居中对齐 centerLeft:垂直居中水平居左对齐 ...

  3. Oracle笔记(十) 约束

    表虽然建立完成了,但是表中的数据是否合法并不能有所检查,而如果要想针对于表中的数据做一些过滤的话,则可以通过约束完成,约束的主要功能是保证表中的数据合法性,按照约束的分类,一共有五种约束:非空约束.唯 ...

  4. Nagios4.x安装配置总结

    1.  Nagios介绍 Nagios是一个监视系统运行状态和网络信息的监视系统.Nagios能监视所指定的本地或远程主机以及服务,同时提供异常通知功能等. Nagios可运行在Linux/Unix平 ...

  5. 从0到1写rtos:事件的挂起

    任务的状态: 未创建:只定义了任务代码,未调用tTaskInit()初始化 就绪:任务已经创建完毕,且等待机会占用CPU运行 运行:任务正在占用CPU运行代码 延时:任务调用tTaskDelay()延 ...

  6. 关于单例模式getInstance()的使用

    /**  * 对象的实例化方法,也是比较多的,最常用的方法是直接使用new,而这是最普通的,如果要考虑到其它的需要,如单实例模式,层次间调用等等. * 直接使用new就不可以实现好的设计好,这时候需要 ...

  7. Hadoop_16_MapRduce_MapTask并行度(切片)的决定机制

    MapTask的并行度决定map阶段的任务处理并发度,进而影响到整个job的处理速度那么,mapTask并行实例是否越多 越好呢?其并行度又是如何决定呢?Mapper数量由输入文件的数目.大小及配置参 ...

  8. okhttp异步请求流程和源码分析

    在上一次[http://www.cnblogs.com/webor2006/p/8023967.html]中对同步请求进行了详细分析,这次来分析一下异步请求,而关于异步请求和同步请求其使用方式基本上差 ...

  9. python : import详解。

    用户输入input() input()函数: 用于从标准输入读取数值. >>> message = input('tell me :') tell me :hahah >> ...

  10. [Python自学] day-20 (Django-ORM、Ajax)

    一.外键跨表操作(一对多) 在 [Python自学] day-19 (2) (Django-ORM) 中,我们利用外键实现了一对多的表操作. 可以利用以下方式来获取外键指向表的数据: def orm_ ...