RABBITMQ's entry HelloWorld (Java) __RABBITMQ

Source: Internet
Author: User
Tags message queue rabbitmq

RABBITMQ Introduction

RABBITMQ is a typical representative of the consumption-producer model, one end writes messages to the message queue, and the other end can read or subscribe to messages in the queue. It is a reusable enterprise message system that implements the AMQP protocol. RABBITMQ is developed in Erlang. The RABBITMQ is also characterized by fault tolerance, thermal updates, distributed caching, and persistence. RABBITMQ can easily build large and available distributed queue message clusters.


RABBITMQ structure diagram:

Some concepts of RABBITMQ:

Broker: In simple terms, Message Queuing server entities.
Exchange: A message switch that specifies what rules the message is routed to and to which queue.
Queue: Message Queuing carrier, where each message is put into one or more queues.
Binding: Binding, which is the purpose of binding exchange and queue to routing rules.
Routing key: Routing key, Exchange is delivering messages based on this keyword.
Vhost: Virtual host, a broker can open multiple vhost, used as separate permissions for different users.
Producer: The message producer is the program that delivers the message.
Consumer: The message consumer is the program that accepts the message.
Channel: Message channel, in each connection of the client, can establish multiple channel, each channel represents a session task.


RABBITMQ is developed in Erlang, but has a driver or client for the primary programming language. We are here to use Java as the client language. Assuming that the environment has been built (see here), first we download the Java Client class library, click here, the following figure is the example of the model:


First create the queue, the producer sends the message to the queue, the consumer takes out the message to the queue, the process is very simple, the following official start!

The steps are as follows:

(i) Creating Access users

[Root@localhost sbin]#./rabbitmqctl add_user test test
Creating user "test" ...
(ii) binding vhost to users and adding permissions

[Root@localhost sbin]#./rabbitmqctl set_permissions-p "/" Test ". *" ". *" ". *"          
Setting permissions for user "test" in Vhost "/" ...
This is where you bind the default Vhost "/", or you can pass it yourself./rabbitmqctl add_vhost xx to add

(iii) preparation of producer procedures and initiation

Import Com.rabbitmq.client.Channel;
Import com.rabbitmq.client.Connection;

Import Com.rabbitmq.client.ConnectionFactory;

    public class Helloworldproducer {private final static String queue_name = "Hello";
        public static void Main (string[] args) throws exception{connectionfactory CF = new ConnectionFactory ();
        RABBITMQ Monitor IP cf.sethost ("192.168.1.96");
        
        RABBITMQ Default listening port, note to remember to open the Port Cf.setport (5672);
        Set access to the user cf.setusername ("test");
        Cf.setpassword ("test");
        Establish connection Connection conn = Cf.newconnection ();

        Create a message channel Channel Channel = Conn.createchannel (); String msg = "Hello World!!!!
        Hello Ah ~ ";
        
        Create the Hello queue Channel.queuedeclare (Queue_name, False, False, false, NULL);
        Send Message Channel.basicpublish ("", queue_name, NULL, msg.getbytes ());
        
        SYSTEM.OUT.PRINTLN ("Send msg" + msg + "to [" + Queue_name + "] QUEUE!"); ChannEl.close ();

    Conn.close (); }

}
You can see there's a message in the Hello queue.
[Root@localhost sbin]#./rabbitmqctl list_queues-p "/"
Listing queues ...
Hello   1
(iv) Preparation of consumer programs and initiation
Import java.io.IOException;
Import java.util.concurrent.TimeoutException;
Import Com.rabbitmq.client.AMQP;
Import Com.rabbitmq.client.Channel;
Import com.rabbitmq.client.Connection;
Import Com.rabbitmq.client.ConnectionFactory;
Import Com.rabbitmq.client.Consumer;
Import Com.rabbitmq.client.DefaultConsumer;

Import Com.rabbitmq.client.Envelope;
    public class Helloworldconsumer {private final static String queue_name = "Hello"; public static void Main (string[] args) throws IOException, timeoutexception {connectionfactory CF = new Connecti
        Onfactory ();
        RABBITMQ Monitor IP cf.sethost ("192.168.1.96");
        
        RABBITMQ Default listening port, note to remember to open the Port Cf.setport (5672);
        Set access to the user cf.setusername ("test");
        Cf.setpassword ("test");
        Establish connection Connection conn = Cf.newconnection ();

        Create a message channel Channel Channel = Conn.createchannel (); Create Hello queue Channel.queuedeclare (Queue_name, False, False, false, NULL);
        System.out.println ("Waiting for msg ..."); Create the consumer and accept the message Consumer Consumer = new Defaultconsumer (channel) {@Override public void Han Dledelivery (String Consumertag, Envelope Envelope, AMQP. Basicproperties properties, byte[] body) throws IOException {String msg = new String (
                Body, "UTF-8");
            System.out.println ("Received is = '" + msg + "");
        }
        };
    Channel.basicconsume (Queue_name, true, consumer); }

}
Run Result:
Then the news in the queue was consumed.

[Root@localhost sbin]#./rabbitmqctl list_queues-p "/"
Listing queues ...
Hello   0
If you don't succeed, it may be a few things:

If the connection is unsuccessful, the IP may be incorrect or the 5672 port is not turned on, you can modify it in Rabbitmq.config (default is {tcp_listeners, [{127.0.0.1, 5672}]})
If you are accessing with guest (default user), the listener host must be localhost
If you are a newly created user, remember to bind Vhost to the user and add permissions
You can get more detailed error information from the RABBITMQ log file Rabbit@localhost.log
Wish you a happy life.













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.