"RabbitMQ" Routing

Source: Internet
Author: User
Tags rabbitmq

Routing

In the previous chapters we built a simple log system. We can broadcast all the log messages to all the receiving end.

In this section we will add a new feature to it-we will allow only a subset of the messages to be subscribed to. For example, we will only target critical error messages to the file (to conserve disk space), while still outputting all log messages in the console.

Bindings

In the previous example, we have created a binding relationship. Recall the code as follows:

Channel.queuebind (QueueName, Exchange_name, "");

A binding refers to the relationship between a switch and a queue. It can be simply understood that the queue is interested in messages in the switch.

The binding requires an additional Routingkey parameter. To avoid confusion with the parameters in the Basic_publish, we now call it binding key. Create a binding with the binding key:

Channel.queuebind (QueueName, Exchange_name, "Black");

The meaning of the binding key is related to the type of switch. The fanout switch we used earlier ignored the binding key directly.

Direct switch

Our previous log system broadcasts all the messages to all the consumers. We want to extend it so that it can be filtered based on the message severity level. For example, we may want a program to write only critical errors to disk, thus avoiding writing warnings or information that can cause wasted disk space.

We used to use the fanout switch, which did not give us much flexibility, just a relentless broadcast.

We will replace it with a direct switch. The routing algorithm for the direct switch is simple-the routing key of a message that will enter the queue must exactly match the binding key of the queue.

To illustrate this point, consider the settings:

You can see that the direct switch is bound to two queues. The first queue binds a binding key called Orange. The second queue has two bindings, one black and one green.

In this setting, messages with routing key orange will be routed to the queue Q1. and routing key for Black and green messages will be routed to Q2. All other messages will be discarded.

Multi-binding

It is legal to bind multiple queues with the same binding key. In our example, we can add a binding between X and Q1, using black as the binding key. In this case, the direct switch broadcasts the message to all matching queues like fanout. A message with routing key black will be sent to both Q1 and Q2.

Send log

We will apply this model to our log system. Unlike Fanout, we will send messages to a direct switch. The log level needs to be provided as routing key. This allows the receiving program to select the level of logging it wants to receive. First, focus on the publication of the log:

First create a switch:

Channel.exchangedeclare (Exchange_name, "direct");

Ready to send a message:

null, Message.getbytes ());

To simplify, we assume that severity can be info,warning,error and so on.

Subscription

Receiving the message is similar to what was said in the previous sections, but with one exception-we need to create a new binding for each level of interest.

Channel.  Queuedeclare().  Getqueue();  For(argvchannel.  Queuebind(queuenameexchange_nameseverity);}        
Putting it all together

Emitlogdirect.java

Importcom.rabbitmq.client.ConnectionFactory;Importcom.rabbitmq.client.Connection;ImportCom.rabbitmq.client.Channel; Public classEmitlogdirect {Private Static FinalString exchange_name = "Direct_logs";  Public Static voidMain (string[] argv)throwsException {connectionfactory Factory=NewConnectionFactory (); Factory.sethost ("LocalHost"); Connection Connection=factory.newconnection (); Channel Channel=Connection.createchannel (); Channel.exchangedeclare (Exchange_name,"Direct"); String severity=getseverity (argv); String message=getMessage (argv); Channel.basicpublish (exchange_name, severity,NULL, Message.getbytes ("UTF-8")); System.out.println ("[x] Sent '" + Severity + "': '" + Message + "'");    Channel.close ();  Connection.close (); }  Private StaticString getseverity (string[] strings) {if(Strings.length < 1)            return"Info"; returnStrings[0]; }  Private StaticString getMessage (string[] strings) {if(Strings.length < 2)            return"Hello world!"; returnJoinstrings (Strings, "", 1); }  Private StaticString Joinstrings (string[] strings, String delimiter,intStartIndex) {    intLength =strings.length; if(length = = 0)return""; if(Length < StartIndex)return""; StringBuilder words=NewStringBuilder (Strings[startindex]);  for(inti = StartIndex + 1; i < length; i++) {words.append (delimiter). Append (Strings[i]); }    returnwords.tostring (); }}

Receivelogsdirect.java

Importcom.rabbitmq.client.*;Importjava.io.IOException; Public classReceivelogsdirect {Private Static FinalString exchange_name = "Direct_logs";  Public Static voidMain (string[] argv)throwsException {connectionfactory Factory=NewConnectionFactory (); Factory.sethost ("LocalHost"); Connection Connection=factory.newconnection (); Channel Channel=Connection.createchannel (); Channel.exchangedeclare (Exchange_name,"Direct"); String QueueName=Channel.queuedeclare (). Getqueue (); if(Argv.length < 1) {System.err.println ("Usage:receivelogsdirect [INFO] [WARNING] [ERROR]"); System.exit (1); }     for(String severity:argv) {channel.queuebind (queuename, exchange_name, severity); } System.out.println ("[*] waiting for messages. To exit Press CTRL + C "); Consumer Consumer=NewDefaultconsumer (channel) {@Override Public voidhandledelivery (String consumertag, Envelope Envelope, AMQP. Basicproperties Properties,byte[] body)throwsIOException {String message=NewString (Body, "UTF-8"); System.out.println ("[x] Received '" + envelope.getroutingkey () + "': '" + Message + "'");    }    }; Channel.basicconsume (QueueName,true, consumer); }}

"RabbitMQ" Routing

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.