1、Rabbitmq hello world

Write pictures described here

RabbitMQ is a message broker: it accepts and forwards messages. You can think of it as a post office: When you want to publish your e-mail in a mailbox, you can determine Mr. Postman will eventually hands the message to your recipient. In this analogy, RabbitMQ is a mailbox, a post office and a postman.

The main difference between the post office and RabbitMQ that it does not deal with the paper, but to accept, store and forward message binary data.

1, and the concept preparation

RabbitMQ messaging and some terms often used.

Production means that sending. A message transmission procedure is a Producer (Manufacturer):

Write pictures described here

Queue (queue) is located within a mailslot RabbitMQ name. Although the RabbitMQ messaging through your application, but they can only be stored in the queue. Queue is limited only by the host memory and disk limits, it is a big message buffer on its nature. Many producers can be sent to a message queue, many consumers may attempt to receive data from a queue. This is our definition of the queue:

Write pictures described here

Consumer reception has a similar meaning. consumer (consumer) is waiting to receive a major news program:

Write pictures described here

In this part of the tutorial, we'll write two programs in Java; send a single message producers, as well as a receiving messages and print out their consumers. We will detail some of the Java API to annotate, to focus on this very simple thing to begin. This is an information transfer "Hello World".

In the following chart, "P" is our producer, and "C" are our consumers. The middle of the box is a queue - RabbitMQ on behalf of consumers saved message buffer.

Write pictures described here

Java client library

RabbitMQ speak a variety of protocols. This tutorial uses AMQP 0-9-1, which is an open, the messaging protocol. In many different languages, RabbitMQ there are many clients. We will use the Java client RabbitMQ provides.
Download the client library and its dependencies (SLF4J API and SLF4J Simple). Copy these files to your working directory, Java files along tutorial.
Please note SLF4J Simple enough for a tutorial, but you should use a sophisticated logging library, just use Logback in the production of the same.
(RabbitMQ Java client also central Maven repository, use groupId to com.rabbitmqand artifactId is amqp-client.)

2, sends a message

Now we have a Java client and its dependencies, we can write some code.

Sending

Write pictures described here

We will call our news publisher (sender) to send a message to our users (receivers) Recv. Post Owner connect to RabbitMQ, send a message, then exit.

Send.java

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

public class Send {

    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws Exception {
        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.75.131");
        factory.setPort(5672);
        factory.setUsername("carl");
        factory.setPassword("198918");
        Connection connection = factory.newConnection();
        Channel channel = connection.createChannel();
        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 + "'");
        channel.close();
        connection.close();
    }

}

The above is what we need to rely on import before rabbitmq-client.

  • First of all, we named this queue, here we named queue name is hello.
  • Then we need to create a connection (connection) is used to connect rabbitmq-server. Abstract connection socket connection, and is responsible for protocol version negotiation and certification, and so on. Here, we connect to the service address rabbitmq own installation and user name / password. If we want to connect to the proxy on another machine, we only need to specify here its name or IP address.
  • Next, we create a channel (channel), which is most of the API used to complete the task lies.
  • In order to send a message, we have to declare a queue for sending us; then we can post a message to the queue: statement queue is idempotent - will only be created if it does not exist. Message content is a byte array, so you can encode anything you like.
  • Finally, we close the channel and connection;

Note: It is possible to send invalid

If this is your first time using RabbitMQ, and you do not see the message "send", then you may feel confused, wondering what could be wrong. Maybe Broke is activated in the absence of enough free disk space conditions (by default it requires at least 200 MB), refused to accept the message. Check the agent log file to identify and reduce the need for restrictions. Profile document will show you how to set up disk_free_limit.

3, receiving a message

Our consumers are push messages from RabbitMQ, so unlike with an announcement of publishers, we'll let it run to listen to the message and print it out.

Receiving

Write pictures described here

Recv.java

public class Recv {

    private final static String QUEUE_NAME = "hello";

    public static void main(String[] args) throws Exception {

        ConnectionFactory factory = new ConnectionFactory();
        factory.setHost("192.168.75.131");
        factory.setPort(5672);
        factory.setUsername("carl");
        factory.setPassword("198918");
        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");
        Consumer consumer = new DefaultConsumer(channel) {
            @Override
            public void handleDelivery(String consumerTag, Envelope envelope,
                                       AMQP.BasicProperties properties, byte[] body)
                    throws IOException {
                String message = new String(body, "UTF-8");
                System.out.println(" [x] Received '" + message + "'");
            }
        };
        channel.basicConsume(QUEUE_NAME, true, consumer);

    }
}

Code message sender and message recipient code is similar, it is also dependent on rabbitmq-client. Additional DefaultConsumer consumer interface is a class implementation, we will use it to push the buffer server gave us the news.

Setting the sender of the message is the same; we open a connection and a channel, and declare that we will be consumed queue. Note that this needs to send the queue name released to the queue to match.

Note that we are here to declare queue. Because we may start before the consumer publisher, so before you try to use it, we want to ensure that there is a queue.

We will tell the server to deliver the message from the queue. Because it will push our messages asynchronously, so we provide a callback, its form is an object, it will buffer these messages until we are ready to use them so far. This is DefaultConsumer subclass done.

4, run

Run Send.java Rabbitmq sends a message to the server, the print log in the control panel:

Connected to the target VM, address: '127.0.0.1:65511', transport: 'socket'
 [x] Sent 'Hello World!'
Disconnected from the target VM, address: '127.0.0.1:65511', transport: 'socket'

Process finished with exit code 0

Rabbitmq can be seen in the control panel, there is a message ready:

Write pictures described here

Then start Recv.java, it will print out a message Send.java Provider that is sent in the console.

Connected to the target VM, address: '127.0.0.1:49238', transport: 'socket'
 [*] Waiting for messages. To exit press CTRL+C
 [x] Received 'Hello World!'

Similarly, we can also see in rabbitmq-admin This news is consumed:

Write pictures described here

Published 173 original articles · won praise 221 · views 700 000 +

Guess you like

Origin blog.csdn.net/u012410733/article/details/81586243