"2" Hello World example

Source: Internet
Author: User
Tags rabbitmq

Introduced
As a message broker middleware, RABBITMQ is designed to be simple: Collect messages and then forward messages. You can think of it as a post office: When you send an email to the mailbox, you're sure that the postman will send the message to the recipient's hand. In this analogy, RABBITMQ actually acts as a mailbox, post office, and Postman's role.
The biggest difference from the post office is that RABBITMQ it does not process paper files, it is responsible for receiving, storing and forwarding binary data message.
Before we get into the details, let's start with some RABBITMQ terminology:

  • Producer: We call the producer the terminal used to send the message, as shown in the figure "P" below:

  • Message Queuing: Message Queuing exists in the RABBITMQ server side; Although messages flow through your application and RABBITMQ server, they can only be stored in RABBITMQ server queues. The queue is unrestricted, and it can store all the messages you send, because it is essentially an infinite buffer. Multiple producers can send messages to a queue at the same time, and multiple consumers can receive data from one queue. Indicates Message Queuing since:

  • Consumer: We say that most of the time is waiting for the client to receive the message, since the consumer:
    "Hello World"
    In this section we will write two programs in Java: A producer to send messages and a consumer to receive messages and print them out. In the implementation process, we focused on how to implement the functionality and the details of the Java API.
    In the following figure, "P" stands for the producer, "C" represents the consumer, and in the middle of the box represents the queue (a buffer where the RABBITMQ is used to hold the message).


    Java-based client:
    RABBITMQ follows the AMQP protocol (Advanced Message Queuing protocol) – This is an open, generic message protocol. There are now many AMQP clients on the web that are implemented in different languages. In this example, we use the Java language client. MAVEN introduces the following:

    <dependency>
    <groupId>com.rabbitmq</groupId>
    <artifactId>rabbitmq-client</artifactId>
    <version>1.3.0</version>
    </dependency>

    Producers
    In this example, we use Send and recv, respectively, to represent the producer and the consumer. Send is used primarily to connect to RABBITMQ server and send a message, and then exit.
    Here is the Send.class implementation:

    import com.rabbitmq.client.connectionfactory;import com.rabbitmq.client.connection;import  com.rabbitmq.client.channel;public class send {  private final static  string queue_name =  "Hello";   public static void main (String[]  ARGV)       throws java.io.ioexception {    //----- ---------1--------------    ConnectionFactory factory = new  ConnectionFactory ();     factory.sethost ("localhost");     connection  connection = factory.newconnection ();    channel channel =  Connection.createchannel ()     //--------------2-----------------     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 + " ");     //---------------3----------------    channel.close ();     connection.close ();   }}

    The first part of the code primarily creates a connection to the RABBITMQ server, which abstracts the socket operation, is responsible for judging the protocol version and identity authentication, and so on. Also because we are building the message broker broker locally, the address of the connection is localhost. If you want to connect to broker broker for another machine, you can specify its domain name or IP address.
    In the second part, we create a channel, and the channel provides us with many APIs for completing the message delivery. For example, we can declare a queue where a queue is used to send messages and to publish messages to claims.
    It is important to note that declaring a queue to be idempotent is only created when the queue does not exist. In addition, because the content of the message is a binary byte array, you can encode any data you need after receiving the data.
    Finally, the third part, we need to turn off channel channels and connections.

    Send failed
    If you're using RABBITMQ for the first time, you might be scratching your heads when you don't see the messages you're sending. It does not matter, it is possible that the broker (the broker, hereafter collectively referred to as broker) does not have enough disk space (by default it needs at least 1Gb of free space) and therefore refuses to receive any messages. You can check the broker's log file to confirm and reduce the limit. The address Http://www.rabbitmq.com/configure.html#config-items explains how to set up Disk_free_limit.

    Consumers
    The following implementation of our customers, it is mainly used to continuously monitor RABBITMQ push messages and print.
    Here is the implementation of Recv.class:

    import com.rabbitmq.client.connectionfactory;import com.rabbitmq.client.connection;import  com.rabbitmq.client.channel;import com.rabbitmq.client.queueingconsumer;public class recv  {  private final static string queue_name =  "Hello";   public  static void main (STRING[]&NBSP;ARGV)       throws  java.io.ioexception,              java.lang.interruptedexception {    //-------------1-------------------     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 ");     //--------------2- ------------------    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 +  ' ' ");     }    } }

    The Queueingconsumer class is primarily used to cache messages pushed by RABBITMQ servers.
    The process of establishing a recv is similar to send; first create a connection to the server and a channel channels (which is called the call channel), and define a queue that we will consume. Note that the queue must match the send, which is the same name.
    In the first part, we declare a queue, and since we may start recv before sender runs, we want to make sure that the queue already exists before we consume the message.
    In the second part we tell the server to push the messages in the Queue_name queue to us. Because the server is sending us an asynchronous push message, we need to provide a callback object Queueingconsumer to cache the message until it is consumed by the program.
    Queueingconsumer.nextdelivery () will clog until the RABBITMQ server pushes the message over.


"2" Hello World example

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.