RabbitMQ getting started-Routing (Routing), rabbitmqrouting

Source: Internet
Author: User

RabbitMQ getting started-Routing (Routing), rabbitmqrouting

Bindings)

 

We have already created bindings in the previous article. The Code is as follows:

 

Channel. QueueBind (queue: queueName, exchange: EXCHANGE_NAME, routingKey: ROUTING_KEY, arguments: null );

 

Bindings refers to the relationship between exchange and queue. It can be simply understood that the queue is interested in messages on the bound switch (exchange), and the switch (exchange) push the messages it receives to the queue.

An additional routingKey is required for binding. To avoid confusion with the routing key parameter in BasicPublish, we call it binding key ), the following describes how to create a binding.

 

Channel. QueueBind (queue: queue, exchange: EXCHANGE_NAME, routingKey: "error", arguments: null );

 

Note:

  • When the routingKey parameter is null, it is also a binding key.
  • The significance of the binding key depends on exchange type. For example, if the exchange type is fanout, the binding key has no significance.

 

Direct exchange)

 

In the previous release and subscription, we have already talked about direct-to-switch. We have learned that the working method of the direct-to-switch is that the switch (exchange) will bind the key (binding key) exactly match with the routing key, and then send the message to the queue that can match successfully.

The entire scenario can be well described:

In this scenario, we can see that the direct connection switch X and the queue (Q1 and Q2) are bound. The Q1 queue uses orange as the binding key, and Q2 has two bindings, respectively using black and green as the binding key ).

In this way, when a message with the route key orange is sent to the switch, it will be routed to the queue Q1, And the next shot with the route key black and green will be routed to Q2, other messages will be discarded.

 

Multiple bindings)

 

Multiple bindings use a binding key to bind to multiple queues. This is completely legal and each queue can obtain identical information.

 

Example

Next, we will use direct exchange to improve the previous log functions.

1. logs with the log level of error are saved to the txt file.

2. log-level logs are output to the console panel.

3. Output all logs to the console panel.

 

Producer RoutingProducer. cs

 

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using System. Threading. Tasks;

Using RabbitMQ. Client;

Using System. Threading;

 

Namespace RabbitMQProducer

{

Public class RoutingProducer

{

Const string EXCHANGE_NAME = "ROUTING_EXCHANGE ";

Static readonly List <string> LEVELS = new List <string> () {"error", "log "};

Public static void Send ()

{

 

ConnectionFactory factory = new ConnectionFactory () {HostName = "localhost "};

Using (IConnection connection = factory. CreateConnection ())

{

Using (IModel channel = connection. CreateModel ())

{

 

// Create a switch with the switch type direct

Channel. ExchangeDeclare (exchange: EXCHANGE_NAME, type: ExchangeType. Direct );

For (int I = 0; I <20; I ++)

{

Thread. Sleep (100 );

String level = GetLevels ();

String message = $ "log information: {I} -- Log level: {level }";

 

// Send the message to the previously created vswitch and set the route key to log level

Channel. BasicPublish (exchange: EXCHANGE_NAME, routingKey: level, basicProperties: null, body: Encoding. UTF8.GetBytes (message ));

Console. WriteLine (message );

}

 

Console. WriteLine ("Press [enter] to exit .");

Console. ReadLine ();

}

}

}

 

Private static string GetLevels ()

{

Return LEVELS [new Random (). Next (0, 2)];

}

}

}

 

Consumer RoutingConsumer. cs

 

Using RabbitMQ. Client;

Using System;

Using System. Collections. Generic;

Using System. Linq;

Using System. Text;

Using System. Threading. Tasks;

Using RabbitMQ. Client. Events;

Using System. IO;

Namespace RabbitMQConsumer

{

Public class RoutingConsumer

{

Const string EXCHANGE_NAME = "ROUTING_EXCHANGE ";

/// <Summary>

/// Whether to use multiple bindings to output all log-level messages to the console

/// By default, only log-level content is output to the console.

/// </Summary>

/// <Param name = "all"> </param>

Public static void Log (bool all = false)

{

Var factory = new ConnectionFactory ()

{

HostName = "127.0.0.1"

};

Using (var connection = factory. CreateConnection ())

{

Using (var channel = connection. CreateModel ())

{

Channel. ExchangeDeclare (exchange: EXCHANGE_NAME, type: ExchangeType. Direct );

// Each time you run the consumer Client, a new queue is created and bound to the corresponding exchange, so that each time a message is sent to exchange, the message is transmitted from exchange to the bound queue.

QueueDeclareOk queue = channel. QueueDeclare ();

String queueName = queue. QueueName;

Channel. QueueBind (queue: queueName, exchange: EXCHANGE_NAME, routingKey: "log", arguments: null );

If (all)

{

Channel. QueueBind (queue: queueName, exchange: EXCHANGE_NAME, routingKey: "error", arguments: null );

}

EventingBasicConsumer consumer = new EventingBasicConsumer (channel );

Consumer. Received + = (sender, e) =>

{

String message = Encoding. UTF8.GetString (e. Body );

Console. WriteLine ($ "LOG -- LOG information: {message }");

};

Channel. BasicConsume (queueName, noAck: true, consumer: consumer );

Console. WriteLine ("Press [enter] to exit .");

Console. ReadLine ();

}

}

}

Public static void Error ()

{

Var factory = new ConnectionFactory () {HostName = "127.0.0.1 "};

Using (IConnection connection = factory. CreateConnection ())

{

Using (IModel channel = connection. CreateModel ())

{

// Create a switch with the switch type direct

Channel. ExchangeDeclare (exchange: EXCHANGE_NAME, type: ExchangeType. Direct );

// Create a new untitled message queue. The queue name is automatically assigned and non-persistent. It is automatically deleted when the queue is not subscribed.

QueueDeclareOk queue = channel. QueueDeclare ();

String queueName = queue. QueueName;

// Bind exchange and queue and set the route key to log-Level error

Channel. QueueBind (queue: queue, exchange: EXCHANGE_NAME, routingKey: "error", arguments: null );

EventingBasicConsumer consumer = new EventingBasicConsumer (channel );

Consumer. Received + = (sender, arg) =>

{

String message = Encoding. UTF8.GetString (arg. Body );

// Write logs to the txt file

Using (StreamWriter writer = new StreamWriter (@ "c: \ log \ log.txt", true, Encoding. UTF8 ))

{

Writer. WriteLine (message );

Writer. Close ();

}

};

Channel. BasicConsume (queue: queueName, noAck: true, consumer: consumer );

}

}

}

}

}

Related Article

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.