【RabbitMQ Tutorials】1 "Hello World!"

Introduction

Prerequisites(n. 预备知识,先决条件(prerequisite复数))

This tutorial assumes(vi. 假定;设想;) RabbitMQ is installed and running on localhost on standard port (5672). In case you use a different host, port or credentials(n. 证书;凭据;), connections settings would require adjusting.

RabbitMQ is a message broker(n. 经纪人,代理 ): it accepts and forwards messages. You can think about it as a post office: when you put the mail that you want posting in a post box, you can be sure that Mr. Postman will eventually deliver the mail to your recipient(n. 容器,接受者;容纳者). In this analogy(n. 类比;类推;类似), RabbitMQ is a post box, a post office and a postman.

The major difference between RabbitMQ and the post office is that it doesn't deal with paper, instead it accepts, stores and forwards binary blobs(n. 斑点; 二进制大型物件) of data ‒ messages.

RabbitMQ, and messaging in general, uses some jargon.

Producing means nothing more than sending. A program that sends messages is a producer :

A queue is the name for a post box which lives inside RabbitMQ. Although messages flow through RabbitMQ and your applications, they can only be stored inside a queue. A queue is only bound by the host's memory & disk limits, it's essentially(adv. 本质上;本来) a large message buffer. Many producers can send messages that go to one queue, and many consumers can try to receive data from one queue. This is how we represent a queue:

Consuming has a similar meaning to receiving. A consumer is a program that mostly waits to receive messages:

Note that the producer, consumer, and broker do not have to reside(vi. 住,居住;属于) on the same host; indeed in most applications they don't.

Hello World!

(using the .NET/C# Client)

In this part of the tutorial we'll write two programs in C#; a producer that sends a single message, and a consumer that receives messages and prints them out. We'll gloss over(v. 掩盖,掩饰;) some of the detail in the .NET API, concentrating on this very simple thing just to get started. It's a "Hello World" of messaging.

In the diagram below, "P" is our producer and "C" is our consumer. The box in the middle is a queue - a message buffer that RabbitMQ keeps on behalf(n. 代表;利益) of the consumer.

The .NET client library
RabbitMQ speaks multiple protocols. This tutorial uses AMQP 0-9-1, which is an open, general-purpose protocol for messaging. There are a number of clients for RabbitMQ in many different languages. We'll use the .NET client provided by RabbitMQ.
The client supports .NET Core as well as .NET Framework 4.5.1+. This tutorial will use .NET Core so you will ensure you have it installed and in your PATH.
You can also use the .NET Framework to complete this tutorial however the setup steps will be different.
The client is distributed via nuget but can also be downloaded as an archive.
This tutorial assumes you are using powershell on windows. On OSX/Linux nearly any shell will work.

Setup

First lets verify that you have .NET Core toolchain(工具链) in PATH: (需要先安装.NET Core,然后再在cmd 执行)

dotnet --help

should produce a help message.

Now let's generate two projects, one for the publisher and one for the consumer:(mv 是Linux 重命名文件名命令,对应window cmd 的rename)

dotnet new console --name Send
mv Send/Program.cs Send/Send.cs (rename Send\Program.cs Send.cs)
dotnet new console --name Receive
mv Receive/Program.cs Receive/Receive.cs (rename Receive\Program.cs Receive.cs)

This will create two new directories named Send and Receive.

Then we add the client dependency.

cd Send
dotnet add package RabbitMQ.Client
dotnet restore
cd ../Receive
dotnet add package RabbitMQ.Client
dotnet restore

Now we have the .NET project set up we can write some code.

Sending

We'll call our message publisher (sender) Send.cs and our message consumer (receiver) Receive.cs. The publisher will connect to RabbitMQ, send a single message, then exit.

In Send.cs, we need to use some namespaces:

using System;
using RabbitMQ.Client;
using System.Text;

Set up the class:

class Send
{
    public static void Main()
    {
        ...
    }
}

then we can create a connection to the server:

class Send
{
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using (var connection = factory.CreateConnection())
        {
            using (var channel = connection.CreateModel())
            {
                ...
            }
        }
    }
}

The connection abstracts the socket connection, and takes care of protocol version negotiation(n. 谈判;转让;协商) and authentication and so on for us. Here we connect to a broker on the local machine - hence(adv. 因此;今后) the localhost. If we wanted to connect to a broker on a different machine we'd simply specify its name or IP address here.

Next we create a channel, which is where most of the API for getting things done resides.

To send, we must declare a queue for us to send to; then we can publish a message to the 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(queue: "hello",
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            string message = "Hello World!";
            var body = Encoding.UTF8.GetBytes(message);

            channel.BasicPublish(exchange: "",
                                 routingKey: "hello",
                                 basicProperties: null,
                                 body: body);
            Console.WriteLine(" [x] Sent {0}", message);
        }

        Console.WriteLine(" Press [enter] to exit.");
        Console.ReadLine();
    }
}

Declaring a queue is idempotent(adj. 幂等的) - it will only be created if it doesn't exist already. The message content is a byte array, so you can encode whatever you like there.

When the code above finishes running, the channel and the connection will be disposed.

Here's the whole Send.cs class.

Sending doesn't work!

If this is your first time using RabbitMQ and you don't see the "Sent" message then you may be left scratching(v. 划伤;擦伤;) your head wondering what could be wrong. Maybe the broker was started without enough free disk space (by default it needs at least 50 MB free) and is therefore refusing to accept messages. Check the broker logfile to confirm and reduce the limit if necessary. The configuration file documentation will show you how to set disk_free_limit.

Receiving

That's it for our publisher. Our consumer is pushed messages from RabbitMQ, so unlike the publisher which publishes a single message, we'll keep it running to listen for messages and print them out.

 The code (in Receive.cs) has almost the same using statements as Send:

 
using RabbitMQ.Client;
using RabbitMQ.Client.Events;
using System;
using System.Text;

Setting up is the same as the publisher; we open a connection and a channel, and declare the queue from which we're going to consume. Note this matches up with the queue that sendpublishes to.

class Receive
{
    public static void Main()
    {
        var factory = new ConnectionFactory() { HostName = "localhost" };
        using (var connection = factory.CreateConnection())
        {
            using (var channel = connection.CreateModel())
            {
                channel.QueueDeclare(queue: "hello",
                                     durable: false,
                                     exclusive: false,
                                     autoDelete: false,
                                     arguments: null);
                ...
            }
        }
    }
}

Note that we declare the queue here, as well. Because we might start the consumer before the publisher, we want to make sure the queue exists before we try to consume messages from it.

We're about to tell the server to deliver(vt. 交付;发表;递送;转发;) us the messages from the queue. Since it will push us messages asynchronously(异步的), we provide a callback. That is what EventingBasicConsumer.Receivedevent handler does.

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(queue: "hello",
                                 durable: false,
                                 exclusive: false,
                                 autoDelete: false,
                                 arguments: null);

            var consumer = new EventingBasicConsumer(channel);
            consumer.Received += (model, ea) =>
            {
                var body = ea.Body;
                var message = Encoding.UTF8.GetString(body);
                Console.WriteLine(" [x] Received {0}", message);
            };
            channel.BasicConsume(queue: "hello",
                                 noAck(autoAck): true,
                                 consumer: consumer);

            Console.WriteLine(" Press [enter] to exit.");
            Console.ReadLine();
        }
    }
}

Here's the whole Receive.cs class.

Putting It All Together

Open two terminals.

Run the consumer:

cd Receive
dotnet run

Then run the producer:

cd Send
dotnet run

The consumer will print the message it gets from the publisher via RabbitMQ. The consumer will keep running, waiting for messages (Use Ctrl-C to stop it), so try running the publisher from another terminal.

posted @ 2017-07-20 13:56  FH1004322  阅读(317)  评论(0)    收藏  举报