Message Queuing (2) Java implementation simple RABBTMQ

Source: Internet
Author: User

Suppose you have the following questions:

1. What should we do if the consumer connection is interrupted?

2. How do I load balance?

3. How to effectively send the data to the relevant recipients? is how to filter

4. How to ensure consumers receive complete and correct data

5. How to get high priority recipients to receive data first

First, "Hello RabbitMQ"

P stands for Producer, c for consumer, red for message queue

Ii. start of the project

1. First create a MAVEN project and then import the Rabbitmqjar package

<?XML version= "1.0" encoding= "UTF-8"?><Projectxmlns= "http://maven.apache.org/POM/4.0.0"Xmlns:xsi= "Http://www.w3.org/2001/XMLSchema-instance"xsi:schemalocation= "http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">    <modelversion>4.0.0</modelversion>    <groupId>Testrabbit</groupId>    <Artifactid>Test</Artifactid>    <version>1.0-snapshot</version>    <Dependencies>        <Dependency>            <groupId>Com.rabbitmq</groupId>            <Artifactid>Amqp-client</Artifactid>            <version>3.6.5</version>        </Dependency>    </Dependencies></Project>

2. Create consumer producer

 Public classProducer { Public Final StaticString queue_name = "Rabbitmq.test";  Public Static voidMain (string[] args)throwsIOException, timeoutexception {//Create a connection factoryConnectionFactory factory =NewConnectionFactory (); //setting RABBITMQ Related informationFactory.sethost ("localhost"); //to create a new connectionConnection Connection =factory.newconnection (); //Create a channelChannel Channel =Connection.createchannel (); //declaring a queueChannel.queuedeclare (Queue_name,false,false,false,NULL); //send a message to the queueString message = "Hello RabbitMQ"; Channel.basicpublish ("", Queue_name,NULL, Message.getbytes ("UTF-8")); System.out.println ("Producer Send:" +message); //close channels and connectionsChannel.close ();    Connection.close (); }}

Queuedeclare The first parameter represents the queue name, the second parameter is persisted (true means that the queue will survive the server restart), and the third parameter is whether the exclusive queue (the private queue that the creator can use, and automatically delete after the disconnection) The fourth parameter is whether the queue is automatically deleted when all consumer client connections are disconnected, and the fifth parameter is the other parameters of the queue.

Basicpublish The first parameter is the switch name, the second parameter is the queue-mapped route key, the third parameter is the other property of the message, and the fourth parameter is the body that sends the message.

3. Create a consumer

Importcom.rabbitmq.client.*;Importjava.io.IOException;Importjava.util.concurrent.TimeoutException; Public classCustomer { Public Final StaticString queue_name = "Rabbitmq.test";  Public Static voidMain (string[] args)throwsIOException, timeoutexception {//Create a connection factoryConnectionFactory factory =NewConnectionFactory (); //Set RABBITMQ addressFactory.sethost ("localhost"); //to create a new connectionConnection Connection =factory.newconnection (); //Create a channelChannel Channel =Connection.createchannel (); //declaring the queue to followChannel.queuedeclare (Queue_name,false,false,false,NULL); System.out.println ("Client waits to receive message"); //The Defaultconsumer class implements the consumer interface by passing in a channel that tells the server which channel we need, and if there is a message on the channel, it executes the callback function HandledeliveryConsumer Comsumer =NewDefaultconsumer (channel) {@Override Public voidHandledelivery (String Consumertag, Envelope Envelope, AMQP. Basicproperties Properties,byte[] body)throwsIOException {String message=NewString (Body, "UTF-8"); System.out.println ("Client receives:" +message);        }        }; //Answering Queue answer automatically--the message acknowledgement mechanism in RABBITMQChannel.basicconsume (Queue_name,true, Comsumer); }}

This method is used to obtain the message sent by the producer, where envelope mainly stores information about the producer (such as switches, routing keys, etc.) body is the message entity.

The results of the operation are as follows:

III. Realization of Task distribution

The advantage of a queue is that it is easy to handle the ability to parallelize, but if we accumulate a lot of work, we need more workers to deal with, so we need to use the distribution mechanism.

Create a new producer NewTask

ImportCom.rabbitmq.client.Channel;Importcom.rabbitmq.client.Connection;Importcom.rabbitmq.client.ConnectionFactory;Importcom.rabbitmq.client.MessageProperties;Importjava.io.IOException;Importjava.util.concurrent.TimeoutException; Public classNewTask { Public Final StaticString task_queue_name = "Task_queue";  Public Static voidMain (String [] args)throwsIOException, timeoutexception {connectionfactory factory=NewConnectionFactory (); Factory.sethost ("LocalHost"); Connection Connection=factory.newconnection (); Channel Channel=Connection.createchannel (); Channel.queuedeclare (Task_queue_name,true,false,false,NULL); //Distributing Messages         for(inti = 0;i<10;i++) {String message= "Hello RabbitMQ" +i; Channel.basicpublish ("", Task_queue_name, Messageproperties.persistent_text_plain,message.getbytes ()); System.out.println ("NewTask Send:" +message);        } channel.close ();    Connection.close (); }}

Then create 2 worker Work1 and WORK2 code like

Importcom.rabbitmq.client.*;Importjava.io.IOException;Importjava.util.concurrent.TimeoutException; Public classWork1 {Private Static FinalString task_queue_name = "Task_queue";  Public Static voidMain (string[] args)throwsIOException, timeoutexception {FinalConnectionFactory factory =NewConnectionFactory (); Factory.sethost ("LocalHost"); Connection Connection=factory.newconnection (); FinalChannel Channel =Connection.createchannel (); Channel.queuedeclare (Task_queue_name,true,false,false,NULL); System.out.println ("Work1 waiting to receive messages"); //the number of fetches per queueChannel.basicqos (1); FinalConsumer Consumer =NewDefaultconsumer (channel) { Public voidHandledelivery (String Consumertag, Envelope Envelope, AMQP. Basicproperties Properties,byte[] body)throwsIOException {String message=NewString (Body, "UTF-8"); System.out.println ("Worker1 received the message:" +message); Try{                    //throw new Exception ();doWork (message); }Catch(Exception ex) {channel.abort (); }finally{System.out.println ("Work1 finished."); Channel.basicack (Envelope.getdeliverytag (),false);        }            }        }; Booleanautoack=false; //message consumption Complete confirmationChannel.basicconsume (Task_queue_name,autoack,consumer); }    Private Static voiddoWork (String Task) {Try{Thread.Sleep (1000);//pause for 1 seconds}Catch(interruptedexception _ignored) {thread.currentthread (). interrupt (); }    }}

Channel.basicqos (1); Ensure that only one distribution at a time, autoack whether the automatic reply, if true, each time the producer sends the message will be removed from memory, then if the consumer program exits unexpectedly, then cannot obtain the data, We did not want this to happen, so we went to the manual reply, whenever the consumer receives and processes the information and notifies the producer, and finally removes the message from the queue. If the consumer exits unexpectedly, if there are other consumers, then the message in the queue will be sent to other consumers, if not, and so on when consumers start sending again.

Two does not throw an exception:

When one is set to an exception, the message is sent to another normal. Wait for the exception program to restart before it will continue to send it.

Message Queuing (2) Java implementation simple RABBTMQ

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.