Clarifying the routing mechanism is the key to understanding the ins and outs of rabbitmq. In the previous example, we often met these three concepts: Exchange, routingkey, and queue. The actual message transmission process is that the message first goes to exchange, and exchange puts the message into Queue according to the corresponding routingkey. If the routingkey does not match, the message is discarded. A picture of online users shows the process:
In version 0.9, amqp has the following four types of exchange: fanout, direct, topic, and headers. The rabbitmq service will create four exchanges in advance after it is started, corresponding to the four types:
Default exchange
If an empty string is used to declare an exchange, the system uses the "AMQ. Direct" exchange. When we create a queue, A routingkey with the same name as the new queue will be bound to this default exchange by default. In the example of sending and receivingCode:
Channel. basicpublish ("","Taskqueue", Properties, bytes );
Because the default exchange is selected in the first parameter, and the declared queue is taskqueue, it creates a routingkey called taskqueue and binds it to the default exchange, as a result, we can write taskqueue In the second parameter routingkey, so that it will find the defined queue with the same name and put the message in.
Direct Exchange
The message sent by direct exchange depends on the routingkey. For example, a direct exchange is defined as X1, and a queue is named Q1 and bound to exchange X1 with routingkey = k1. When a routekey is K2, the message reaches X1, then, only when k1 = k2 can the message be sent to Q1. The code example is as follows:
Channel. exchangedeclare ("X1","Direct"); Channel. queuedeclare ("Q1",True,False,False,Null); Channel. queuebind ("Q1","X1","K1"); Channel. basicpublish ("X1","K1",Null, Bytes );
So that Q1 can receive the message.
If there are two recipientsProgramIf both the same queue and the same routingkey are used to bind direct exchange, the distribution behavior is load balancing. That is to say, the first one is received by program 1, and the second one is received by Program 2, and so on.
If two receiving programs use their own queue, but use the same routingkey to bind direct exchange, the distribution is replicated, that is, each program will receive a copy of the message. The behavior is equivalent to the fanout type exchange.
Official Image Display direct exchange:
Fanout exchange
Fanout exchange is easy to understand. It is a simple broadcast and ignores the routingkey. Therefore, as long as a queue is bound to fanout exchange, messages sent through this exchange will be sent to those bound queue, whether or not you have entered the routingkey.
You can use it extensively in scenarios such as broadcast messages or distributed system message synchronization.
Official image display:
Topic exchange
Exchange of topic type gives us more flexibility. By defining the routingkey, you can select to subscribe to certain messages. In this case, the routingkey is an expression. Exchange matches the bound routingkey to determine whether to put messages in the corresponding queue. There are two types of expression symbols: # And *.
* (Asterisk): represents any word. For example, *. A matches a. a, B. a, c. A, and so on.
# (Well number): Any zero or multiple words in the code. Example: #. A will match a. a, AA. A, AAA. A, etc.
Topic exchange sometimes acts like other types of exchange, for example:
When the routingkey only has the # number, its behavior is the same as that of fanout.
When there is no routingkey or empty string, it performs the same behavior as direct.
Note that a symbol represents a word rather than a character. In rabbitmq, words are defined in expressions separated by periods.
You can bind a queue to exchange multiple times:
Channel. queuebind (queue_name,"X1","Lazy .#"); Channel. queuebind (queue_name,"X1","*. *. Rabbit");
The code above indicates that this queue can start with lazy and end with. Rabbit.
You can understand the rules through some tests. However, during the test, you must note that every time you modify the expression, you need to reset rabbitmq. Because it can be bound multiple times, all the expressions you modified earlier will be recorded and matched.
Reset command (rabbitmq is run on the console ):
Headers exchange
The headers type exchange is rarely used. It is also a routing method that ignores the routingkey. Headers is used for matching. Headers is a key-Value Pair and can be defined as hashtable. The sender defines some key-value pairs when sending the message, and the receiver can also bind some key-value pairs. If the two match, the corresponding queue can receive the message. Two matching methods are available: all and any. The two methods must be defined at the acceptor using the key value "X-mactch. All indicates that multiple key-value pairs must be satisfied, while any indicates that the code can satisfy only one key-value pair. The routingkey of the previous exchange must be in the string format, but headers exchange does not have this requirement, because the value of the key-value pair can be of any type. The sample code is as follows:
Sender:
Channel. exchangedeclare ("X1","Headers");
Ibasicproperties properties = channel. createbasicproperties ();
Properties. headers =NewHashtable ();
Properties. headers. Add ("Key1", 123 );
Properties. headers. Add ("Key2", 345 );
Xmlserializer xs =NewXmlserializer (Typeof(Requestmessage ));
Memorystream MS =NewMemorystream ();
Xs. serialize (the MS, message );
Byte[] Bytes = Ms. toarray ();
Channel. basicpublish ("X1","", Properties, bytes );
Acceptor:
Channel. exchangedeclare ("X1","Headers");
// Create a queue randomly
StringQueue_name = channel. queuedeclare ("Headerssubscriber2",True,False,False,Null);
// Bind
Idictionary ht =NewHashtable ();
Ht. Add ("X-match","Any");
Ht. Add ("Key1", 12345 );
Ht. Add ("Key2", 34567 );
Channel. queuebind (queue_name,"X1","", HT );
// Define the consumer of this queue
Queueingbasicconsumer consumer =NewQueueingbasicconsumer (Channel );
Channel. basicconsume (queue_name,True, Consumer );
While(True)
{
Basicdelivereventargs Ea =
(Basicdelivereventargs) Consumer. queue. dequeue ();
Byte[] Bytes = EA. Body;
Xmlserializer xs =NewXmlserializer (Typeof(Requestmessage ));
Using(Memorystream MS =NewMemorystream (bytes ))
{
Requestmessage message = (requestmessage) XS. deserialize (MS );
Console. writeline ("Receive a message, ID :"+ Message. messageid +"Message :"+ Message. Message );
}
}
Click here to download the test code