RabbitMQ学习之:(三)第一个RMQ的程序 (转贴+我的评论)

RabbitMQ for Windows: Building Your First Application

Posted by Derek Greer on March 7, 2012

This is the second installment to the RabbitMQ for Windows series.  In our first installment, we walked through getting RabbitMQ installed on a Microsoft Windows machine. In this installment, we’ll discuss a few high-level concepts and walk through creating our first RabbitMQ application.

Basic Concepts

To being, let’s discuss a few basic concepts. Each of the examples we’ll be working through will have two roles represented: a Producer and a Consumer. A Producer sends messages and a Consumer receives messages.

Messages are basically any blob of bytes you’d like to send. This could be a simple ASCII string, JavaScript Object Notation (JSON), or a binary-serialized object.

Messages are sent to Queues.  A Queue is a First-In-First-Out (FIFO) data structure. You can think of a queue as a sort of pipe where you put messages in one side of the pipe and the messages arrive at the other end of the pipe.

The following diagram depicts these concepts:

We’ll introduce other concepts further into the series, but that’s the basics. Let’s move on to creating our first example.

Hello, World!

Our first application will be an obligatory “Hello World” example.  We’ll create a Publisher application which sends the string “Hello, World!” to a RabbitMQ queue and a Consumer application which receives the message from the queue and displays it to the console.

For all of our examples, we’ll be using the official RabbitMQ .Net client availablehere.  This library is also available via NuGet, so if you have the NuGet Package Manager installed you can retrieve it through the “Tools->Library Package Manager” menu item, or if you have the NuGet.exe command line utility then you can issue the following command in the directory you’d like it installed to:

nuget install RabbitMQ.Client

Create the Producer

To start, let’s create a new empty solution named HelloWorldExample (File->New->Project->Other Project Types->Visual Studio Solutions->Blank Solution). Once you have that created, add a new project of type “Console Application” to the solution and name it “Producer”.

Next, add a reference to the RabbitMQ.Client.dll assembly.

The first thing we’ll need to do for our producer is to establish a connection to the RabbitMQ server using a ConnectionFactory:

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

The ConnectionFactory has a number of properties that can be set for our connection. In this example, we’re establishing a connection using the default connection settings which assumes you have the RabbitMQ Windows service running on your local development machine. If you’ve installed it on a different machine then you’ll need to set the Host property of the connectionFactory instance to the DNS name where you’ve installed RabbitMQ.

Next, we need to create a Channel:

IModel channel = connection.CreateModel();

A channel is a light-weight connection which RabbitMQ uses to enable multiple threads of communication over a single TCP/IP socket.Note that the actual type created is RabbitMQ.Client.IModel. In most RabbitMQ client libraries the term channel is used, but for some reason the authors of the .Net client library chose to use the term “Model”[PunCha:其实这点很烦人,这个没理由叫做Model的啊!而且Web管理界面都称之为Channel,这个作者真不知道怎么想的)]. Descriptive, eh? We’ll use the instance name of “channel” to be more descriptive.

Next, we need to create a queue:

channel.QueueDeclare(“hello-world-queue”, false, false, false, null);

This creates a queue on the server named “hello-world-queue” which is non-durable (won’t survive a server restart), is non- exclusive (other channels can connect to the same queue), and is not auto-deleted once it’s no longer being used.  We’ll discuss these parameters in more detail further in our series.

Next, we’ll declare a byte array containing a UTF8-encoded array of bytes from the string “Hello, World!” and use the BasicPublish() method to publish the message to the queue:

byte[] message = Encoding.UTF8.GetBytes("Hello, World!");
channel.BasicPublish(string.Empty, “hello-world-queue”, null, message);

Again, don’t worry about understanding the parameters just yet.[PunCha:第一个参数是空字符串,代表无名(默认的)Exchange,第二个参数是RoutingKey,第三个是一些属性] We’ll get to that soon enough.

Finally, we’ll prompt the user to press a key to exit the application and close our channel and connection:

Console.WriteLine("Press any key to exit");
Console.ReadKey();
channel.Close();
connection.Close();

Here’s the full Producer listing:

using System.Text;
using RabbitMQ.Client;

namespace Producer
{
  class Program
  {
    static void Main(string[] args)
    {
      var connectionFactory = new ConnectionFactory();
      IConnection connection = connectionFactory.CreateConnection();
      IModel channel = connection.CreateModel();
      channel.QueueDeclare("hello-world-queue", false, false, false, null);
      byte[] message = Encoding.UTF8.GetBytes("Hello, World!");
      channel.BasicPublish(string.Empty, "hello-world-queue", null, message);
      Console.WriteLine("Press any key to exit");
      Console.ReadKey();
      channel.Close();
      connection.Close();
    }
  }
}

Create the Consumer

Next, let’s create our Consumer application. Add a new Console Application to the solution named “Consumer” and add a reference to the RabbitMQ.Client assembly. We’ll start our consumer with the same connection, channel, and queue declarations:

var connectionFactory = new ConnectionFactory();
IConnection connection = connectionFactory.CreateConnection();
IModel channel = connection.CreateModel();
channel.QueueDeclare("hello-world-queue", false, false, false, null);

Next, we’ll use the BasicGet() method to consume the message from the queue “hello-world-queue”:

BasicGetResult result = channel.BasicGet("hello-world-queue", true);

Next, we’ll check to ensure we received a result. If so, we’ll convert the byte array contained within the Body property to a string and display it to the console:

if (result != null)
{
  string message = Encoding.UTF8.GetString(result.Body);
  Console.WriteLine(message);
}

Lastly, we’ll prompt the user to press a key to exit the application and close our channel and connection:

Console.WriteLine("Press any key to exit");
Console.ReadKey();
channel.Close();
connection.Close();

Here’s the full Consumer listing:

using System;
using System.Text;
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.QueueDeclare("hello-world-queue", false, false, false, null);
      BasicGetResult result = channel.BasicGet("hello-world-queue", true);
      if (result != null)
      {
        string message = Encoding.UTF8.GetString(result.Body);
        Console.WriteLine(message);
      }
      Console.WriteLine("Press any key to exit");
      Console.ReadKey();
      channel.Close();
      connection.Close();
    }
  }
}

To see the application in action, start the Publisher application first and then start the Consumer application. If all goes well, you should see the Consumer application print the following:

Hello, World!
Press any key to exit

Congratulations! You’ve just completed your first RabbitMQ application.  Next time, we’ll take a closer look at the concepts used within our Hello World example.

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

时间: 2024-12-16 14:03:21

RabbitMQ学习之:(三)第一个RMQ的程序 (转贴+我的评论)的相关文章

RabbitMQ学习(三)订阅/发布

RabbitMQ学习(三)订阅/发布 1.RabbitMQ模型 前面所学都只用到了生产者.队列.消费者.如上图所示,其实生产者并不直接将信息传输到队列中,在生产者和队列中间有一个交换机(Exchange),我们之前没有使用到交换机是应为我们没有配置交换机,使用了默认的交换机. 有几个可供选择的交换机类型:直连交换机(direct), 主题交换机(topic), (头交换机)headers和 扇型交换机(fanout) 这里我们使用扇形交换机做一个简单的广播模型:一个生产者和多个消费者接受相同消息

DuiLib学习笔记2——写一个简单的程序

我们要独立出来自己创建一个项目,在我们自己的项目上加皮肤这才是初衷.我的新建项目名为:duilibTest 在duilib根目录下面有个 Duilib入门文档.doc 我们就按这个教程开始入门 首先新建一个win32项目 去DuiLib根目录,把目录下DuiLib文件夹拷贝到新建项目的根目录.再把这个项目添加进我们解决方案中. 从教程里面把以下代码粘贴到我们项目的stdafx.h中 // Duilib使用设置部分 #pragma once #define WIN32_LEAN_AND_MEAN

rabbitmq学习(三) —— 工作队列

工作队列,又称任务队列,主要思想是避免立即执行资源密集型任务,并且必须等待完成.相反地,我们进行任务调度,我们将一个任务封装成一个消息,并将其发送到队列.工作进行在后台运行不断的从队列中取出任务然后执行.当你运行了多个工作进程时,这些任务队列中的任务将会被工作进程共享执行. 这个概念在 Web 应用程序中特别有用,在短时间 HTTP 请求内需要执行复杂的任务. 准备工作 现在,假装我们很忙,我们使用 Thread.sleep 来模拟耗时的任务. 发送端 public class NewTask

Scala学习2 ———— 三种方式完成HelloWorld程序

三种方式完成HelloWorld程序 分别采用在REPL,命令行(scala脚本)和Eclipse下运行hello world. 一.Scala REPL. 按照第一篇在windows下安装好scala后,直接Ctrl+R,然后在运行命令窗里输入scala,或者输入cmd后,进入命令行在输入scala. 然后我们输入 print("Hello World!") 看下结果: 第一种方式运行完毕. 注意:前两行命令使用了Tab键,可以像bash一样有补全的功能哦! 二.Scala脚本完成H

RabbitMQ学习(三).NET Client之Publish/Subscribe

3 Publish/Subscribe Sending messages to many consumers at once Python | Java | Ruby | PHP| C# 转载请注明出处:jiq?钦's technical Blog Publish/Subscribe (using the .NET Client) 前面的教程我们已经学习了如何创建工作队列,工作队列背后的假设是每一个任务都被准确地递送给一个worker进行处理.这里我们将介绍完全不同的模式,即一个消息可以递送给多

rabbitMQ学习笔记(三) 消息确认与公平调度消费者

从本节开始称Sender为生产者 , Recv为消费者   一.消息确认 为了确保消息一定被消费者处理,rabbitMQ提供了消息确认功能,就是在消费者处理完任务之后,就给服务器一个回馈,服务器就会将该消息删除,如果消费者超时不回馈,那么服务器将就将该消息重新发送给其他消费者 默认是开启的,在消费者端通过下面的方式开启消息确认,  首先将autoAck自动确认关闭,等我们的任务执行完成之后,手动的去确认,类似JDBC的autocommit一样 QueueingConsumer consumer

RabbitMQ学习第三记:发布/订阅模式(Publish/Subscribe)

工作队列模式是直接在生产者与消费者里声明好一个队列,这种情况下消息只会对应同类型的消费者. 举个用户注册的列子:用户在注册完后一般都会发送消息通知用户注册成功(失败).如果在一个系统中,用户注册信息有邮箱.手机号,那么在注册完后会向邮箱和手机号都发送注册完成信息.利用MQ实现业务异步处理,如果是用工作队列的话,就会声明一个注册信息队列.注册完成之后生产者会向队列提交一条注册数据,消费者取出数据同时向邮箱以及手机号发送两条消息.但是实际上邮箱和手机号信息发送实际上是不同的业务逻辑,不应该放在一块处

Python学习第三天(一个简单制作导入模块)

Python一个简单的模块制作和导入 一个简单的模块 [[email protected] python]# cat my.py name = 'I am wuang!' 导入模块 >>> import my >>> print my.name I am wuang! 直接导入模块属性名字 >>> from my import name >>> print name I am wuang!

tensorflow框架学习(三)—— 一个简单的神经网络示例

一.神经网络结构 定义一个简单的回归神经网络结构: 数据集为(xi,yi),数据的特征数为1,所以x的维度为1. 输入层1个神经元. 隐藏层数为1,4个神经元. 输出层1个神经元. 隐藏层的激活函数为f(x)=x,输出层的激活函数为ReLU 结构图如下: 二.代码示例 相关函数说明: tf.random_normal :用于生成正太分布随机数矩阵的tensor,tensorFlow有很多随机数函数,可以查找官方文档获得. tf.zeros :用于生成0矩阵的tensor,tf.ones可以用来获