RabbitMQ getting started

Source: Internet
Author: User

RabbitMQ getting started

The previous article was translated by RabbitMQ's official guide. Due to my limited level, improper translation is inevitable. If you find anything wrong, please contact me to correct it in time. Now, the text begins:

RabbitMQ is a message proxy. This principle is very simple, that is, by receiving and forwarding messages. You can think of it as a post office: when you send a package to the post office, you will believe that the postman will eventually send the mail to the recipient. RabbitMQ is like a mailbox, post office, or postman.

The main difference between the post office and RabbitMQ is that RabbitMQ accepts, stores, and forwards messages in binary form instead of processing files.

RabbitMQ, we use some standard names during message transmission.

The production process is like the sending process. The sending program is a producer. We use "P" to describe it.

A queue is like a mail box. It is located inside RabbitMQ. Although messages are circulated through RabbitMQ and your applications, they are only stored in the queue. A queue has no range restrictions. You can store a queue as much as you want, which is essentially an infinitely large cache. Multiple producers can send messages in one queue, and multiple consumers can receive messages in the same message queue. The queue is drawn like this and the name is on it:

The consumption process is similar to receiving. A consumer is usually a program waiting to receive messages. We use "C" to describe:

Note that the producer, consumer, and agent do not have to be on one machine. In fact, most applications do not have to be on one machine.

 

"Hello World"

 

(Using the java client)

In this section, we will use java to write two programs, one producer that sends simple messages and the other consumer that receives and outputs messages. We will ignore some Java API details. In order to start simply selecting this simple thing, this is a "Hello World" message.

Java client library
RabbitMQ follows the AMQP protocol, which is an open and common message protocol. There are several AMQP clients in different languages. We use Java clients provided by RabbitMQ.
Download the client library package, verify the signature, decompress it to your working path, and extract the JAR file from the decompressed path:

$ unzip rabbitmq-java-client-bin-*.zip$ cp rabbitmq-java-client-bin-*/*.jar ./

(The RabbitMQ Java client also exists in the Maven Central Library,groupIdYescom.rabbitmq,artifactIdYesamqp-client.)

Now that we have a Java client and a dependent file, we can write some code.

 

Send

We will ask our message senders to send messages, and our recipients will receive messages. The sender connects to RabbitMQ, sends a simple message, and then exits.

InSend.java, We need to introduce some classes:

import com.rabbitmq.client.ConnectionFactory;import com.rabbitmq.client.Connection;import com.rabbitmq.client.Channel;

Create this class and name the queue:

public class Send {  private final static String QUEUE_NAME = "hello";  public static void main(String[] argv)      throws java.io.IOException {      ...  }}

Next, we will create a server connection:

    ConnectionFactory factory = new ConnectionFactory();    factory.setHost("localhost");    Connection connection = factory.newConnection();    Channel channel = connection.createChannel();

Abstract socket connection, pay attention to Protocol version processing and authorization, and so on.
Here we connect to the proxy on the local machine, so it islocalhost. If you want to connect to a proxy on a different machine, you only need to specify its host name and IP address.

Next we will create a channel where most of the APIs for obtaining operations are located.

For sending, we must declare a sending queue and then send the message to this queue:

channel.queueDeclare(QUEUE_NAME, false, false, false, null);

String message = "Hello World!";channel.basicPublish("", QUEUE_NAME, null, message.getBytes());System.out.println(" [x] Sent '" + message + "'");

Declaring a queue is idempotent-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.

Lastly, we close the channel and the connection;
Declaring a queue is idempotent. It is created only when the queue to be declared does not exist. The message content is a binary array, so you can encode it as you like.

channel.close();

connection.close();

Here's the whole Send. java class.

Sending does not work

If you are using RabbitMQ for the first time and you have not seen the "Sent" message, you may be scratching your ears to find out what the problem is. It may be because the proxy does not have enough space when it is started (it requires at least 1 Gb space by default), so the message is rejected. Check the agent's log file to identify this problem and reduce the limit size if necessary. The configuration file will show you how to setdisk_free_limit.

 

Receive

The above code is to build our sender. Our receiver extracts messages from RabbitMQ, so instead of sending a simple message as the sender, we need to keep running the listening message and output the message.

The code in Recv. java has almost the same reference as that in Send:

import com.rabbitmq.client.ConnectionFactory;
import com.rabbitmq.client.Connection;
import com.rabbitmq.client.Channel;
import com.rabbitmq.client.QueueingConsumer;

This additionalQueueingConsumerClass is used to cache information sent from the server.

Like creating a sender, we open a connection and a channel to declare a queue to be consumed. Be sure to match the sent queue.

             java.lang.InterruptedException {  private final static String QUEUE_NAME = "hello";  public static void main(String[] argv)      throws java.io.IOException,             java.lang.InterruptedException {    ConnectionFactory factory = new ConnectionFactory();    factory.setHost("localhost");    Connection connection = factory.newConnection();    Channel channel = connection.createChannel();    channel.queueDeclare(QUEUE_NAME, false, false, false, null);    System.out.println(" [*] Waiting for messages. To exit press CTRL+C");    ...    }}

Note that a queue is also declared here. We thought we might start the receiver before the sender. Before we get the message from the sender, we want to determine whether the queue actually exists.
We notify the server to send messages to us through this queue. Therefore, the server asynchronously pushes messages to us. Here we provide a callback object to cache messages until we are ready to use them again. This isQueueingConsumerWhat you do.

QueueingConsumer consumer = new QueueingConsumer(channel);channel.basicConsume(QUEUE_NAME, true, consumer);while (true) {  QueueingConsumer.Delivery delivery = consumer.nextDelivery();  String message = new String(delivery.getBody());  System.out.println(" [x] Received '" + message + "'");}

QueueingConsumer.nextDelivery()It will be blocked until another message from the server arrives.

This is the entire Recv. java class.

 

Put all together

You can compile these files in the class path of the RabbitMQ Java client:

$ javac -cp rabbitmq-client.jar Send.java Recv.java

To run them, you needrabbitma-client.jarAnd its dependent files on the class path. On a terminal, run the sender:

$ java -cp .:commons-io-1.2.jar:commons-cli-1.1.jar:rabbitmq-client.jar Send

Then, run the receiver:

$ java -cp .:commons-io-1.2.jar:commons-cli-1.1.jar:rabbitmq-client.jar Recv

In windows, we use semicolons instead of colons to separate the options on the class path.

The recipient will output the message from the sender obtained from RabbitMQ. The receiver will keep running and wait for the message (UseCtrl-CSo try to run the sender on another terminal.
If you want to test the queue, try to userabbitmqctl list_queues0.

Hello World!

Move the time to the second part to build a simple work queue.

Prompt
To save the input, you can set the class path to the environment variable.

\$ export CP=.:commons-io-1.2.jar:commons-cli-1.1.jar:rabbitmq-client.jar\$ java -cp $CP Send

Or in Windows:

\> set CP=.;commons-io-1.2.jar;commons-cli-1.1.jar;rabbitmq-client.jar\> java -cp %CP% Send

Install RabbitMQ in CentOS 5.6

Detailed installation record of RabbitMQ client C ++

Try RabbitMQ in Python

Production and implementation of RabbitMQ Cluster Environment

Use PHP + RabbitMQ in Ubuntu

Process of installing RabbitMQ on CentOS

RabbitMQ concept and Environment Construction

For more details, please continue to read the highlights on the next page:

  • 1
  • 2
  • 3
  • 4
  • 5
  • 6
  • Next Page

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.