RabbitMQ学习之:(三)第一个RMQ的程序 (转贴+我的评论)
RabbitMQ for Windows: Building Your First Application
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.
RabbitMQ学习之:(三)第一个RMQ的程序 (转贴+我的评论)的更多相关文章
- RabbitMQ学习系列三-C#代码接收处理消息
RabbitMQ学习系列三:.net 环境下 C#代码订阅 RabbitMQ 消息并处理 http://www.80iter.com/blog/1438251320680361 http://www. ...
- RabbitMQ学习系列三:.net 环境下 C#代码订阅 RabbitMQ 消息并处理
上一篇已经讲了Rabbitmq如何在Windows平台安装 不懂请移步: RabbitMQ学习系列二:.net 环境下 C#代码使用 RabbitMQ 消息队列 一.理论 .net环境下,C#代码订阅 ...
- rabbitmq学习(三) —— 工作队列
工作队列,又称任务队列,主要思想是避免立即执行资源密集型任务,并且必须等待完成.相反地,我们进行任务调度,我们将一个任务封装成一个消息,并将其发送到队列.工作进行在后台运行不断的从队列中取出任务然后执 ...
- Scala学习2 ———— 三种方式完成HelloWorld程序
三种方式完成HelloWorld程序 分别采用在REPL,命令行(scala脚本)和Eclipse下运行hello world. 一.Scala REPL. 按照第一篇在windows下安装好scal ...
- rabbitmq学习(三):rabbitmq之扇形交换机、主题交换机
前言 上篇我们学习了rabbitmq的作用以及直连交换机的代码实现,这篇我们继续看如何用代码实现扇形交换机和主题交换机 一.扇形交换机 1.生产者 /** * 生产者 */ public class ...
- rabbitMQ学习笔记(三) 消息确认与公平调度消费者
从本节开始称Sender为生产者 , Recv为消费者 一.消息确认 为了确保消息一定被消费者处理,rabbitMQ提供了消息确认功能,就是在消费者处理完任务之后,就给服务器一个回馈,服务器就会将 ...
- RabbitMQ学习第三记:发布/订阅模式(Publish/Subscribe)
工作队列模式是直接在生产者与消费者里声明好一个队列,这种情况下消息只会对应同类型的消费者. 举个用户注册的列子:用户在注册完后一般都会发送消息通知用户注册成功(失败).如果在一个系统中,用户注册信息有 ...
- rabbitMQ学习(三)
订阅/广播模式 发送端: import java.io.IOException; import com.rabbitmq.client.ConnectionFactory; import com.ra ...
- 【Python学习笔记三】一个简单的python爬虫
这里写爬虫用的requests插件 1.一般那3.x版本的python安装后都带有相应的安装文件,目录在python安装目录的Scripts中,如下: 2.将scripts的目录配置到环境变量pa ...
随机推荐
- Hadoop_19_MapReduce&&Yarn运行机制
1.YARN的运行机制 1.1.概述: Yarn集群:负责海量数据运算时的资源调度,集群中的角色主要有:ResourceManager.NodeManager Yarn是一个资源调度(作业调度和集群资 ...
- linux——常用命令
学习linux命令地址: 学习命令地址,可参考http://linux.51yip.com/ 在文件中搜索指定字符串 grep -i "requirepass" redis.con ...
- 说说lock到底锁谁(II)?
摘要 今天在园子里面有园友反馈关于[C#基础]说说lock到底锁谁?文章中lock(this)的问题.后来针对文章中的例子,仔细想了一下,确实不准确,才有了这篇文章的补充,已经对文章中的demo进行修 ...
- python+Appium自动化:toast定位
Toast简介 Toast是一种简易的消息提示框. 当视图显示给用户,在应用程序中显示为浮动.和Dialog不一样的是,它永远不会获得焦点,无法被点击. 用户将可能是在中间键入别的东西.Toast类的 ...
- C语言Ⅰ作业-05
这个作业属于哪个课程 C语言程序设计Ⅰ 这个作业要求在哪里 https://www.cnblogs.com/tongyingjun/p/11722665.html 我在这个课程的目标是 熟练掌握如何用 ...
- 前端知识体系:JavaScript基础-原型和原型链-理解JavaScript的执行上下文栈,可以应用堆栈信息快速定位问题
理解JavaScript的执行上下文栈,可以应用堆栈信息快速定位问题(原文文档) 1.什么是执行上下文: 简而言之,执行上下文就是当前JavaScript代码被解析和执行时所在环境的抽象概念,Java ...
- windows下C语言头文件的运用
头文件 singnext.dingswords printf("终止我每丝呼吸,让心灵穿透所有的秘密\n"); 头文件 singtocj.h printf("当无数的日月 ...
- GNS3错误’Could not start Telnet console with command 'Solar-PuTTY.exe‘
这个报错是由于电脑中没有安装Solar-Putty导致的.直接安装一个solar-putty或者putty,然后在gns3上方工具栏点击:edit - preferences - general -c ...
- HDU 6061 - RXD and functions | 2017 Multi-University Training Contest 3
每次NTT都忘记初始化,真的是写一个小时,Debug两个小时- - /* HDU 6061 - RXD and functions [ NTT ] | 2017 Multi-University Tr ...
- SpringBoot AOP注解式拦截与方法规则拦截
AOP的本质还是动态代理对方法调用进行增强. SpringBoot 提供了方便的注解实现自定义切面Aspect. 1.使用需要了解的几个概念: 切面.@Aspect 切点.@Pointcut. 通知. ...