RABBITMQ Introduction (ii)--DIRECT exchanger

Source: Internet
Author: User

Getting Started with RABBITMQ (i) We talked about three of the most important types of exchange: Direct, fanout, and topic.

Here we take a look at the simplest use of the direct switch.

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7E/E6/wKiom1cMWZOC4_2LAAEtryR2zDM706.png "title=" 2.PNG " alt= "Wkiom1cmwzoc4_2laaetryr2zdm706.png"/>

Here is the test code:

package com.jaeger.exchange.direct;import java.io.ioexception;import  java.util.concurrent.timeoutexception;import org.junit.test;import com.rabbitmq.client.channel; Import com.rabbitmq.client.connection;import com.rabbitmq.client.connectionfactory;public class  Producer {private static final String MY_EXCHANGE_NAME =  "Myexchange" ;p rivate static final string my_routing_key =  "Myroutingkey";p rivate static  final String MY_QUEUE_NAME =  "Myqueue";p rivate static final string  DIRECT =  "DIRECT";p rivate static final string host =  " 172.19.64.21 ";p rivate static final string user = " Jaeger ";p rivate static  final String PASSWORD =  "Root";p Rivate static final int port  = 5672; @Testpublic  void createexchangeanDqueue ()  throws ioexception, timeoutexception {connectionfactory connectionfactory  = new connectionfactory (); Connectionfactory.sethost (HOST); Connectionfactory.setusername (USER); Connectionfactory.setpassword (PASSWORD); Connectionfactory.setport (PORT); Connection connection = connectionfactory.newconnection (); Channel channel = connection.createchannel ();//  Create a DIRECT type of Exchangechannel.exchangedeclare (My_exchange_name, direct);//  Create a Queuechannel.queuedeclare (my_queue_name, false, false, false, null);//  Create a routing key that binds EXCHANGE and the QUEUE together Channel.queuebind (my_queue_name, my_exchange_name, my_ Routing_key); Channel.close (); Connection.close ();} @Testpublic  void produce ()  throws ioexception, timeoutexception { Connectionfactory connectionfactory = new connectionfactory (); ConnectionFactory.setHost ( HOST); connectionfactory.setusErname (USER); Connectionfactory.setpassword (PASSWORD); Connectionfactory.setport (PORT); Connection connection = connectionfactory.newconnection (); Channel channel = connection.createchannel (); string message =  "hello  world!"; * Send a message to RABBITMQ. We specify the name of Exchange and Routing key here, and RABBITMQ will look for exchange with this name, and if it finds one, it will check to see if the exchange is bound to the same name as we specified routing  key, found to put the message into the Routing key corresponding queue inside */channel.basicpublish (My_exchange_name, my_routing_key,  null, message.getbytes ("Utf-8")); System.out.println ("sent "  + message +  "'"); Channel.close (); Connection.close ();} @Testpublic  void consume ()  throws IOException, TimeoutException,  Interruptedexception{connectionfactory connectionfactory = new connectionfactory (); Connectionfactory.sethost (HOST); Connectionfactory.setusername (USER); Connectionfactory.setpassword (PASSWORD); Connectionfactory.setport (PORT); Connection&nbSp;connection = connectionfactory.newconnection (); Channel channel = connection.createchannel (); Consumer consumer = new defaultconsumer (channel)  {@Overridepublic  void  Handledelivery (STRING CONSUMERTAG, ENVELOPE ENVELOPE, AMQP. Basicproperties properties,byte[] body)  throws IOException {String message  = new string (body,  "UTF-8"); System.out.println ("received "  + message +  "'");}; Channel.basicconsume (My_queue_name, true, consumer); Thread.Sleep (1000);}}

Briefly introduce the connection and channel of the RABBITMQ before speaking to the direct switch.

The client-to-RABBITMQ connection is built via TCP, why not use connection directly as a database? Because TCP is very resource-intensive to build and destroy, the task for a messaging server is to handle a huge amount of messages, which is obviously inappropriate if each message is created and consumed by a TCP connection.

To solve this problem, the Channel,channel equivalent of a virtual connection within a TCP connection is introduced. The generation and consumption of messages is done through the channel, and each channel is assigned a unique ID to distinguish between different channel to avoid interfering with each other. Just like a fiber cable, every fiber bundle in a network cable can be used to deliver messages without interfering with each other.


Let's take a look at the effect of the direct switch, first executing the Createexchangeandqueue method:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M00/7E/E3/wKioL1cMYNqCNHxsAAC0IOiF9BI184.png "style=" float: none; "title=" 3.PNG "alt=" Wkiol1cmynqcnhxsaac0ioif9bi184.png "/>

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7E/E6/wKiom1cMYCaRR3PqAABuSjXk7dM619.png "style=" float: none; "title=" 4.PNG "alt=" Wkiom1cmycarr3pqaabusjxk7dm619.png "/>

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7E/E3/wKioL1cMYNqyn6qJAABgBBDMLuY417.png "style=" float: none; "title=" 5.PNG "alt=" Wkiol1cmynqyn6qjaabgbbdmluy417.png "/>

As you can see from the background, the exchange, routing key, and queue we have specified are created correctly, and the names are the names we specify.

Next we are running the produce method to send a message to RABBITMQ:

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M01/7E/E6/wKiom1cMYdKj6DaGAABDckAmzDQ957.png "title=" 6.PNG " alt= "Wkiom1cmydkj6dagaabdckamzdq957.png"/>

You can see that a message has been added to the Myqueue queue. Finally run the consume method to consume this message:

650) this.width=650; "src=" Http://s1.51cto.com/wyfs02/M01/7E/E4/wKioL1cMZvbwQeUQAAAiuQLk4Vc540.png "title=" 7.PNG " alt= "Wkiol1cmzvbwqeuqaaaiuqlk4vc540.png"/>

For the consumer side, just know the name of the queue. For the sender, you need to know the name of exchange and routing key, which is relatively less important than the name of the queue.



Finally, we analyze the RABBITMQ (a) inside the Send method, the method does not seem to specify the name of Exchange and routing key, and do not do queue and exchange binding operations, why can also send success? Here is the code snippet:

Public void send ()  {    connectionfactory connectionfactory =  new connectionfactory ();     connectionfactory.sethost (HOST);     connectionfactory.setusername (USER);     connectionfactory.setpassword (PASSWORD);     connectionfactory.setport (PORT);    try {         connection connection = connectionfactory.newconnection ();         channel channel = connection.createchannel ();         channel.queuedeclare (Queue_name, false, false, false,  null); //a        string message =  "Hello   World! ";         channel.basicpublish ("", queue_name, null,  Message.getbytes ("UTF-8 ")  //b        system.out.println (" Sent  " +  message +  "'");         channel.close ();         connection.close ();    } catch  (IOException e )  {        e.printstacktrace ();    }  catch  (timeoutexception e)  {        e.printstacktrace () ;     }}

At a we created a queue called queue_name, which does not correspond to any of the routing keys, nor does it declare any exchange.

At B when we send a message, the specified exchange is an empty string, routing key is actually the name of the queue, not that Exchange is based on routing key to decide which queue to put in, how to use the queue name?


For the above questions, let's explain below:

RABBITMQ has a default exchange, and his name is an empty string. Every queue we create is bound to this exchange (so when we bind exchange and queue through a custom routing key, the queue is actually secretly bound to this default Exchange). The name of the middle routing key is the name of the queue. So exchange in the method above B is the default Exchange, and routing key looks like the name of the queue, actually because routing key has the same name as the queue name. We have modified the above produce method:

@Testpublic  void produce ()  throws IOException, TimeoutException {     connectionfactory connectionfactory = new connectionfactory ();     connectionfactory.sethost (HOST);     connectionfactory.setusername (USER);     connectionfactory.setpassword (PASSWORD);     connectionfactory.setport ( PORT);     connection connection = connectionfactory.newconnection ();     channel channel = connection.createchannel ();     String  message =  "hello  world!";     //  Here we send the message to the default Exchange,routing key name is the name of the queue      Channel.basicpublish ("",  my_queue_name, null, message.getbytes ("Utf-8"));     system.out.println ("sent "  + message +  "'");    &nbSp;channel.close ();     connection.close ();} 

The message was successfully placed in the Myqueue queue via the default Exchange and routing key.

650) this.width=650; "src=" Http://s4.51cto.com/wyfs02/M02/7E/E5/wKioL1cMitvCWDhlAAHPGuuHgrI050.png "style=" float: none; "title=" 8.PNG "alt=" Wkiol1cmitvcwdhlaahpguuhgri050.png "/>

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/7E/E8/wKiom1cMiieyXZhXAAFPbYVGCK0442.png "style=" float: none; "title=" 9.PNG "alt=" Wkiom1cmiieyxzhxaafpbyvgck0442.png "/>

650) this.width=650; "src=" Http://s5.51cto.com/wyfs02/M00/7E/E5/wKioL1cMitzRsSQFAABTHsxwagY388.png "style=" float: none; "title=" 10.PNG "alt=" Wkiol1cmitzrssqfaabthsxwagy388.png "/>


This article is from the "Bronze Gong" blog, please be sure to keep this source http://jaeger.blog.51cto.com/11064196/1762941

RABBITMQ Introduction (ii)--DIRECT exchanger

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.