RABBITMQ Second article: Java Simple implementation RABBITMQ

Source: Internet
Author: User
Tags rabbitmq

Preface: Here I will use Java to implement the RABBITMQ simply. Below we take the following question to step by step understanding and learning rabbitmq.

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

2: How to do load balancing

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

One: "Hello RabbitMQ"

Here is a picture, where p represents the producer, c is the consumer, and the red part is Message Queuing

two: Project start

2.1: First introduce the RABBITMQ jar package

<dependency>            <groupId>com.rabbitmq</groupId>            <artifactid>amqp-client</ artifactid>            <version>3.6.5</version> </dependency>

2.2: Create consumer producer

/** * Message Creator */public class Producer {public    final static String queue_name= "Rabbitmq.test";    public static void Main (string[] args) throws IOException, timeoutexception {        //Create connection factory        ConnectionFactory Factory = new ConnectionFactory ();        Set RABBITMQ related information        factory.sethost ("localhost");      Factory.setusername ("LP");      Factory.setpassword ("");     Factory.setport (2088);        Create a new connection        Connection Connection = factory.newconnection ();        Create an aisle Channel        = Connection.createchannel ();  declares a queue        Channel.queuedeclare (Queue_name, False, False, false, NULL);        String message = "Hello RabbitMQ";        Send message to queue        channel.basicpublish ("", queue_name, NULL, Message.getbytes ("UTF-8"));        System.out.println ("Producer Send +" + message + "'");        Close the channel and connect the        channel.close ();        Connection.close ();    }}

Note 1:queuedeclare The first parameter indicates the queue name, whether the second parameter is persisted (true indicates that the queue will survive the server restart), whether the third parameter is an exclusive queue (the private queue that the creator can use, the automatic deletion after 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 for the queue

Note 2:basicpublish The first parameter is the switch name, the second parameter is the queue-mapped route key, the third parameter is the other attribute of the message, and the fourth parameter is the body that sends the information

2.3: Create Consumer

public class Customer {private final static String queue_name = "Rabbitmq.test"; public static void Main (string[] args) throws IOException, TimeoutException {//Create connection factory ConnectionFactory FA        Ctory = new ConnectionFactory ();        Set RABBITMQ address Factory.sethost ("localhost");        Create a new connection Connection Connection = Factory.newconnection ();        Create an aisle Channel = Connection.createchannel ();        Declares the queue to be followed Channel.queuedeclare (Queue_name, False, False, true, NULL);        System.out.println ("Customer waiting Received messages"); The Defaultconsumer class implements the Consumer interface by passing in a channel,//telling the server that we need the message for that channel, and if there is a message in the channel, the callback function is executed handledelivery Consumer Consu Mer = new Defaultconsumer (channel) {@Override public void Handledelivery (String consumertag, Envelo PE envelope, AMQP. Basicproperties properties, byte[] body) throws IOException {StRing message = new String (Body, "UTF-8");            System.out.println ("Customer Received" + Message + "'");        }        };    Auto reply Queue Answer--message acknowledgement mechanism in RABBITMQ Channel.basicconsume (Queue_name, true, consumer); }

We can see in the preceding code the same as the generator, followed by the acquisition of information sent by the producer, where envelope mainly store producer-related information (such as switches, routing key, etc.) body is the message entity.

2.4: Run Results

Producers:

Consumers:

Three: Achieve task distribution

Work queue

One of the advantages of a queue is that it is easy to deal with the ability to parallelize, but if we accumulate a lot of work, we need more workers to deal with, it is necessary to use the distribution mechanism.

We create a new producer NewTask

public class NewTask {    private static final String task_queue_name= "Task_queue";    public static void Main (string[] args) throws IOException, timeoutexception {        connectionfactory factory=new ConnectionFactory ();        Factory.sethost ("localhost");        Connection connection=factory.newconnection ();        Channel Channel=connection.createchannel ();   Channel.queuedeclare (task_queue_name,true,false,false,null);        Distribution information for        (int i=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

public class Work1 {private static final String Task_queue_name = "Task_queue";  public static void Main (string[] args) throws IOException, TimeoutException {final ConnectionFactory factory = new        ConnectionFactory ();        Factory.sethost ("localhost");        Connection Connection = Factory.newconnection ();        Final Channel channel = Connection.createchannel ();        Channel.queuedeclare (Task_queue_name, True, False, false, NULL);        System.out.println ("Worker1 Waiting for Messages");        The number of Channel.basicqos (1) per acquisition from the queue;  Final 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 ("Worker1 Received ' "+ Message +" ' ");                    Try {throw new Exception ();                DoWork (message);                }catch (Exception e) {channel.abort ();                    }finally {System.out.println ("Worker1 done");                Channel.basicack (Envelope.getdeliverytag (), false);        }            }        };        Boolean autoack=false;    Message consumption complete Confirmation channel.basicconsume (task_queue_name, autoack, consumer); } private static void DoWork (String Task) {try {thread.sleep (1000);//pause 1 seconds} catch (Interr        Uptedexception _ignored) {thread.currentthread (). interrupt (); }    }}

Note: Channel.basicqos (1); guarantee to distribute only one at a time. Autoack whether the automatic reply, if true, each time the producer sends the message will be removed from the memory, then if the consumer program exits unexpectedly, then cannot obtain the data, we certainly do not want to appear such situation, so only then go to the manual reply, Whenever the consumer receives and processes the information then notifies the creator. Finally, the message is removed 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.

On the above we left a question to continue the next article

RABBITMQ Second article: Java Simple implementation RABBITMQ

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.