RABBITMQ Study First: Connect with Java RABBITMQ

Source: Internet
Author: User
Tags server port rabbitmq

1. What is RABBITMQ

MQ (Message queue): A queue of messages that is designed by the server to store a large number of messages and provides a way for the client to operate the queue: the production queue (adding data to the queue), the consumption queue (fetching data from the queue).    RABBITMQ is a typical application based on Message Queuing. RABBITMQ In addition to the normal production and consumption functions, there are some advanced features: Fair distribution, polling distribution, road by mode, wildcard mode, publish subscription, queue persistence.

2, Java implementation of RABBITMQ connection

2.1. RABBITMQ Client Jar Package

<Dependency>    <groupId>Com.rabbitmq</groupId>    <Artifactid>Amqp-client</Artifactid>    <version>4.0.2</version></Dependency>

2.2. Java Connection RABBITMQ Tool class

 Public classconnectionutil{Private StaticLogger Logger = Logger.getlogger (connectionutil.class);  Public StaticConnection getconnection () {Try{Connection Connection=NULL; //Define a connection factoryConnectionFactory factory =NewConnectionFactory (); //set the server-side address (domain address/IP)Factory.sethost ("127.0.0.1"); //Set server port numberFactory.setport (5672); //setting up a virtual host (equivalent to a library in a database)Factory.setvirtualhost ("/"); //Set user nameFactory.setusername ("admin"); //Set PasswordFactory.setpassword ("888888"); Connection=factory.newconnection (); returnconnection; }        Catch(Exception e) {return NULL; }    }}

2.3. Simple producer-consumer model

Work map taken from the production and consumption model of the official website (RabbitMQ)

P: Producer of messages

C: Consumer of the message

Red: Queue

The producer sends the message to the queue and the consumer gets the message from the queue.

2.4. Producer (Send)

 Public classsend{//Queue name    Private Static FinalString queue_name = "Test_simple_queue";  Public Static voidMain (string[] args) {Try        {            //Get ConnectionsConnection Connection =connectionutil.getconnection (); //get a channel from the connectionChannel Channel =Connection.createchannel (); //declaring queuesChannel.queuedeclare (Queue_name,false,false,false,NULL); String message= "This is a simple queue"; //Send MessageChannel.basicpublish ("", Queue_name,NULL, Message.getbytes ("Utf-8")); System.out.println ("[Send]:" +message);            Channel.close ();        Connection.close (); }        Catch(IOException |timeoutexception e)        {E.printstacktrace (); }    }}

Operation Result:
[Send]:this is simple queue

2.5. Consumer (Receive)

 Public classreceive{//Queue name    Private Static FinalString queue_name = "Test_simple_queue";  Public Static voidMain (string[] args) {Try        {            //Get ConnectionsConnection Connection =connectionutil.getconnection (); //get a channel from the connectionChannel Channel =Connection.createchannel (); //declaring queuesChannel.queuedeclare (Queue_name,false,false,false,NULL); //Define consumerDefaultconsumer consumer =NewDefaultconsumer (channel) {//Execute callback method when message arrives@Override Public voidhandledelivery (String consumertag, Envelope Envelope, basicproperties properties,byte[] body)throwsIOException {String message=NewString (Body, "utf-8"); System.out.println ("[Receive]:" +message);            }            }; //Listening QueueChannel.basicconsume (Queue_name,true, consumer); }        Catch(IOException | shutdownsignalexception |consumercancelledexception e)        {E.printstacktrace (); }}} Run result: [Receive]:this is simple queue

Summary: The simple producer-consumer model realizes the production data of the producer to the queue, and the consumer can listen to the queue continuously and fetch the data from the queue.

Note: This article only represents personal understanding and views yo! I have no relationship with the company and the group!

RABBITMQ Study First: Connect with Java RABBITMQ

Related Article

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.