RABBITMQ Example Tutorial: Route selection

Source: Internet
Author: User
Tags rabbitmq

In the previous example, we built a simple log system to send log messages to multiple recipients via broadcast. This article describes how to subscribe to a subset of messages. For example, we can write critical error messages to a log file and print all the log messages in the console.


  Message binding (Bindings)


In the previous example, we used the following code to bind again.


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


The binding expresses the relationship between the switch and the queue, which can be understood as the queue's interest in the messages in the switch.


The parameters of the binding are routingkey, to avoid confusion, we refer to the Basic_publish parameter as the binding key, and the following is an example of binding binding using a keyword.


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

It indicates that the binding keyword depends on the switch type, and it ignores the bound keyword for the fanout switch we defined earlier. The message is sent to all subscribers.


  Direct switch (direct exchange)


In the previous example, we broadcast all the messages to all consumers, and now we want to do some improvement on the original basis to filter the log messages. For example, we can save disk space by writing a log file with a bad log.


The fanout switch is less flexible, it just broadcasts all the messages blindly, and now uses the direct switch instead. The algorithm of the direct switch is very simple-when the Binding keyword matches the message's routing keyword, the message is passed to the queue.


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/74/65/wKiom1Yb_BaBH97lAABhpyYpPKI061.jpg "title=" Route-01.png "alt=" Wkiom1yb_babh97laabhpyyppki061.jpg "/>


As shown, the x switch is bound to two queues Q1 and Q2. The Q1 queue binds the Orange keyword, and the Q2 queue binds the green and black keywords. Messages with the orange routing key in the route are forwarded to Q1, and messages with black or green keywords are forwarded to Q2, and other messages are discarded.


  Multiple bindings (multiple bindings)


650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M02/74/62/wKioL1Yb_DSCBsmYAABZ02FvZAM164.jpg "title=" Route-02.png "alt=" Wkiol1yb_dscbsmyaabz02fvzam164.jpg "/>


It is legal for a route to bind to multiple queues using the same binding code. , x routers are bound to Q1 and Q2 using black code. In this case, the direct switch will broadcast the message to all queues, just like the fanout switch.


  Submit Log


We continue to use the log system as our model. We use the direct switch instead of the fanout switch and log level severity as the routing code so that we can decide which messages to receive based on the log level.


(1) Creating a direct switch


Channel.exchangedeclare (Exchange_name, "direct");


(2) Prepare to send a message


Channel.basicpublish (exchange_name, severity, NULL, message.getbytes ());

(3) Divide the log level into: info,warning and error, creating different bindings based on the log level.


Message Subscription


Receiving the message is the same as in the previous example, except that a new binding is created for each Severity.


String queuename = Channel.queuedeclare (). Getqueue (); for (String severity:argv) {channel.queuebind (QueueName, EXCHAN Ge_name, severity);}


  Big Summary

650) this.width=650; "src=" Http://s3.51cto.com/wyfs02/M00/74/65/wKiom1Yb_LPjrxnCAAB_Hhio3IQ776.jpg "title=" Route-03.png "alt=" Wkiom1yb_lpjrxncaab_hhio3iq776.jpg "/>


  Emitlogdirect.java

package com.favccxx.favrabbit;import com.rabbitmq.client.channel;import  com.rabbitmq.client.connection;import com.rabbitmq.client.connectionfactory;public class  emitlogdirect {private static final string exchange_name =  "Direct_logs"; Public static void main (STRING[]&NBSP;ARGV)  throws exception {connectionfactory  factory = new connectionfactory (); Factory.sethost ("localhost"); Connection connection = factory.newconnection (); Channel channel = connection.createchannel (); Channel.exchangedeclare (EXCHANGE_NAME,  " Direct "); string[] serveritys = {"Debug",  "info",  "warning",  "error"}; string[] messages = {"this is a debug message!",  "This is a  info message! ", " this is a warning message! ", " This is a  error message!"};for (int i=0; i<serveritys.length; i++) {channel.basicpublish (EXCHANGE_NAME,  Serveritys[i], null, messages[i].getbytes ("UTF-8")); System.out.println (" [x] Sent " " + serveritys[i] + " ': ' " +  messages[i] +  "'");} Channel.close (); Connection.close ();}}


The console output reads as follows


[x] Sent ' debug ': ' This is a debug message! ' [x] Sent ' info ': ' This is a info message! ' [x] Sent ' warning ': ' This is a warning message! ' [x] Sent ' ERROR ': ' This is a error message! '


To simplify the implementation of the code, we used a for loop to receive log information of various severity levels, respectively. But in a real-world application, we might need a four-to-five receiver.


  Receivelogsdirect.java


Package com.favccxx.favrabbit;import java.io.ioexception;import com.rabbitmq.client.amqp;import  com.rabbitmq.client.Channel;import com.rabbitmq.client.Connection;import  com.rabbitmq.client.connectionfactory;import com.rabbitmq.client.consumer;import  com.rabbitmq.client.defaultconsumer;import com.rabbitmq.client.envelope;public class  receivelogsdirect {private static final string exchange_name =  "Direct_logs ";p Ublic static void main (STRING[]&NBSP;ARGV)  throws exception { Connectionfactory factory = new connectionfactory (); Factory.sethost ("localhost"); Connection connection = factory.newconnection (); Channel channel = connection.createchannel (); Channel.exchangedeclare (EXCHANGE_NAME,  " Direct "); String queuename = channel.queuedeclare (). Getqueue (); string[] serveritys = {  "Debug",  "INFO ", " Warning ", " error  };for  (String severity : serveritys)  { Channel.queuebind (queuename, exchange_name, severity); Consumer consumer = new defaultconsumer (channel)  {@Overridepublic  void  Handledelivery (STRING&NBSP;CONSUMERTAG,&NBSP;ENVELOPE&NBSP;ENVELOPE,&NBSP;AMQP. Basicproperties properties,byte[] body)  throws IOException {String message  = new string (body,  "UTF-8"); System.out.println (" [x] Received " " + envelope.getroutingkey ()  + " ': ' "  + message +  "'");}; Channel.basicconsume (Queuename, true, consumer);}}}


 The console output reads as follows


[x] Received ' debug ': ' This is a debug message! ' [x] Received ' info ': ' This is a info message! ' [x] Received ' warning ': ' This is a warning message! ' [x] Received ' ERROR ': ' This is a error message! '


This article is from the "This person's IT World" blog, be sure to keep this source http://favccxx.blog.51cto.com/2890523/1702327

RABBITMQ Example Tutorial: Route selection

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.