RABBITMQ Learning IV: Route mode (direct)

Source: Internet
Author: User

1. What is the routing mode (direct)

  The routing pattern is when the switch is used, the producer specifies the route to send the data, and the consumer binds the route to accept the data. Unlike the Publish/subscribe model, the Publish/Subscribe mode receives data that the producer pushes over to the switch as long as the queue that binds the switch is received. While routing mode adds a routing setting, when a producer sends data to the switch, it declares the route sent to the switch and receives the data only if the consumer's queue is bound to the switch and the route is declared. Legend of route patterns taken from the official website (RabbitMQ)

P: Producer of messages

X: Switch

Red: Queue

C1,C2: Message Consumers

Error,info,warning: Routing

  a log processing example: the system needs to be analyzed for the log, first of all the log level of the log needs to be saved, followed by the error log level of the log needs to be processed separately. You can then use the route pattern to handle the claims that the switch uses the routing pattern, and that each log level log corresponds to a route (error,info,warning). Declares that a save log queue is used to accept all logs, bind the switch, and bind all routes. Declares that the second queue is used to process the error level log, binds the switch and binds only the error route. The following is a code explanation. ( run two consumers first, running the producer.) If the queue is not bound to the switch in advance, the message will not be sent to any queue if the producer is run directly .

2. Producer (Send) code

 Public classsend{//Switch Name    Private Final StaticString exchange_name = "Test_exchange_direct"; //Route name Warning    Private Final StaticString routing_key_warning = "WARNING"; //Routing Name Info    Private Final StaticString routing_key_info = "INFO"; //Routing name Error    Private Final StaticString routing_key_error = "ERROR";  Public Static voidMain (string[] args) {Try        {            //Get ConnectionsConnection Connection =connectionutil.getconnection (); //get a channel from the connectionChannel Channel =Connection.createchannel (); //declaring the SwitchChannel.exchangedeclare (Exchange_name, "direct"); String message= "This is warning log"; //Send message (Warning level log)Channel.basicpublish (Exchange_name, routing_key_warning,NULL, Message.getbytes ("Utf-8")); System.out.println ("[Send]:" +message); //Send Message (Info level log)Message = "This is info log"; Channel.basicpublish (Exchange_name, Routing_key_info,NULL, Message.getbytes ("Utf-8")); System.out.println ("[Send]:" +message); //Send Message (Error level log)Message = "This is the error log"; Channel.basicpublish (Exchange_name, Routing_key_error,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 warning log
[Send]:this is info log
[Send]:this is error log

3. Consumer 1 (Receivealllog)

 Public classreceivealllog{//Switch Name    Private Final StaticString exchange_name = "Test_exchange_direct"; //Route name Warning    Private Final StaticString routing_key_warning = "WARNING"; //Routing Name Info    Private Final StaticString routing_key_info = "INFO"; //Routing name Error    Private Final StaticString routing_key_error = "ERROR"; //Queue name    Private Static FinalString queue_name = "Test_queue_save_all_log";  Public Static voidMain (string[] args) {Try        {            //Get ConnectionsConnection Connection =connectionutil.getconnection (); //get a channel from the connection            FinalChannel Channel =Connection.createchannel (); //declaring the SwitchChannel.exchangedeclare (Exchange_name, "direct"); //declaring queuesChannel.queuedeclare (Queue_name,false,false,false,NULL); //bind a queue to a switch (specify Route info,error,warning)Channel.queuebind (queue_name, Exchange_name, Routing_key_info);            Channel.queuebind (Queue_name, Exchange_name, Routing_key_error);            Channel.queuebind (Queue_name, Exchange_name, routing_key_warning); //guaranteed to distribute only one at a time            intPrefetchcount = 1;            Channel.basicqos (Prefetchcount); //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 ("[Test_queue_save_all_log] Receive message:" +message); Try                    {                        //consumer rest 2s processing businessThread.Sleep (1000); }                    Catch(interruptedexception e) {e.printstacktrace (); }                    finally                    {                        //Manual AnswerChannel.basicack (Envelope.getdeliverytag (),false);            }                }            }; //set up a manual answer            BooleanAutoack =false; //Listening QueueChannel.basicconsume (queue_name, autoack, consumer); }        Catch(IOException e) {e.printstacktrace (); }    }}

Operation Result:

[Test_queue_save_all_log] Receive Message:this is warning log
[Test_queue_save_all_log] Receive Message:this is info log
[Test_queue_save_all_log] Receive Message:this is error log

4. Consumer 2 (Receiveerrorlog)

 Public classreceiveerrorlog{//Switch Name    Private Final StaticString exchange_name = "Test_exchange_direct"; //Routing name Error    Private Final StaticString routing_key_error = "ERROR"; //Queue name    Private Static FinalString queue_name = "Test_queue_handel_error";  Public Static voidMain (string[] args) {Try        {            //Get ConnectionsConnection Connection =connectionutil.getconnection (); //get a channel from the connection            FinalChannel Channel =Connection.createchannel (); //declaring queuesChannel.queuedeclare (Queue_name,false,false,false,NULL); //bind a queue to a switch (Specify routing error)Channel.queuebind (queue_name, Exchange_name, Routing_key_error); //guaranteed to distribute only one at a time            intPrefetchcount = 1;            Channel.basicqos (Prefetchcount); //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 ("[Test_queue_handel_error] Receive message:" +message); Try                    {                        //consumer rest 2s processing businessThread.Sleep (1000); }                    Catch(interruptedexception e) {e.printstacktrace (); }                    finally                    {                        //Manual AnswerChannel.basicack (Envelope.getdeliverytag (),false);            }                }            }; //set up a manual answer            BooleanAutoack =false; //Listening QueueChannel.basicconsume (queue_name, autoack, consumer); }        Catch(IOException e) {e.printstacktrace (); }    }}

Operation Result:
[Test_queue_handel_error] Receive Message:this is error log

Summarize:

1. Two queue consumers set a different route, and the received message is not the same. In the routing mode, the decision to push the message to the queue depends primarily on the route, not the switch.

  2. The mode must set the switch and declare the routing mode: Channel.exchangedeclare (exchange_name, "direct");

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

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.