[. NET] RabbitMQ behavior art,. netrabbitmq
RabbitMQ behavior art
RabbitMQ: a message system developed by Erlang Based on the AMQP system protocol.
Advantages: robust, easy to use, open-source, and support for various popular languages (such as Python, java, and. NET.
MQ (Message Queue): Short for Message Queue, is a communication mechanism between applications.
Purpose: To improve the server throughput and performance by asynchronous processing, you do not need to call back immediately to obtain results and perform time-consuming operations. For example, logging.
Figure: simple communication mode and changes after MQ is added
End A: The producer writes (inserts) messages to the queue. MQ (Queue): middleware, message carrier. End B: the consumer reads (retrieves) messages from the queue. MQ features: a form of consumer-producer model. Environment Construction
1. Official website download installation package: http://www.rabbitmq.com /;
2. During installation, you will be prompted to download the Erlang language environment;
3. Start the installed Service: RabbitMQ;
Rabbitmq-plugins enable rabbitmq_management
5. Default url: http: // localhost: 15672 /#/
[Note] the producer and consumer do not need to reside on the same server.
Producer. cs
1 public class Producer 2 {3 public static void Send () 4 {5 var factory = new ConnectionFactory {HostName = "localhost"}; 6 7 // create a connection object, based on Socket 8 using (var connection = factory. createConnection () 9 {10 // create a channel and session 11 using (var channel = connection. createModel () 12 {13 // declare queue 14 channel. queueDeclare (queue: "hello", // queue name 15 durable: false, // persistence 16 exclusive: false, // exclusive 17 autoDelete: false ,// Automatically delete 18 arguments: null); 19 20 const string message = "Hello World! "; 21 var body = Encoding. UTF8.GetBytes (message); 22 23 channel. basicPublish (exchange: "", // switch name 24 routingKey: "hello", // route key 25 basicProperties: null, 26 body: body ); 27} 28} 29} 30}
[Note] If the queue name already exists, it will not be created again. If the queue already exists, an exception occurs when you modify the parameters in the channel. QueueDeclare () method.
[Note] the message content is a byte array.
Consumer. cs
1 class Consumer 2 {3 public static void Receive () 4 {5 var factory = new ConnectionFactory () {HostName = "localhost"}; 6 7 using (var connection = factory. createConnection () 8 {9 using (var channel = connection. createModel () 10 {11 channel. queueDeclare (queue: "hello", 12 durable: false, 13 exclusive: false, 14 autoDelete: false, 15 arguments: null); 16 17 // create a Consumer based on this queue, bind event 18 var consumer = new EventingBasicConsumer (channel); 19 consumer. stored ed + = (model, ea) => 20 {21 var body = ea. body; // message Body 22 var message = Encoding. UTF8.GetString (body); 23 Console. writeLine ("[x] Received {0}", message); 24}; 25 26 // start consumer 27 channel. basicConsume (queue: "hello", // queue name 28 noAck: true, // false: manual response; true: automatic response 29 consumer: consumer); 30 31 Console. read (); 32} 33} 34} 35}
[Question] Why does the queue (channel. QueueDeclare () be declared again in the consumer's class? -- Because the receiver may start before the sender starts, this is out of warranty.
Example 2: publishing/subscription mode diagram: Direct
Figure: Fanout
Figure: Topic
-- The above three pictures Source: http://m.blog.csdn.net/article/details? Id = 52262850
Here, a vswitch named "logs" is created and its type is broadcast (fanout: all received messages can be broadcast to all known queues ).
Channel. ExchangeDeclare (exchange: "logs", // switch name type: "fanout"); // exchange type
2. Temporary queue
As a consumer, we sometimes only need some new (or empty) queues. In this case, a better way is to make it automatically generate a queue with a random name. Secondly, when the queue connection is interrupted, the corresponding consumer is automatically deleted.
Creates a queue with non-persistent, exclusive, and automatic deletion features (when no parameter is set ).
var queueName = channel.QueueDeclare().QueueName;
3. Binding
[Question] What else do I need when I have Exchange and channel? -- We need to create a bridge between Exchange and channel. This bridge is called Binding ).
channel.QueueBind(queue: queueName, exchange: "logs", routingKey: "");
1 class Producer 2 {3 public static void Send () 4 {5 var factory = new ConnectionFactory () 6 {7 HostName = "localhost", 8 Port = 5672, 9 UserName = "guest", 10 Password = "guest" 11}; 12 13 using (var connection = factory. createConnection () 14 {15 using (var channel = connection. createModel () 16 {17 channel. exchangeDeclare (exchange: "logs", // switch name 18 type: "fanout"); // switch type 19 20 // Guid21 var message = Guid. newGuid (). toString (); 22 var body = Encoding. UTF8.GetBytes (message); 23 channel. basicPublish (exchange: "logs", 24 routingKey: "", 25 basicProperties: null, 26 body: body); 27 28 Console. writeLine ("[x] Sent {0}", message); 29} 30 31 Console. writeLine ("Press [enter] to exit. "); 32 Console. readLine (); 33} 34} 35}Producer. cs // producer 1 class Reciver 2 {3 public static void Recive () 4 {5 var factory = new ConnectionFactory () 6 {7 HostName = "localhost", 8 Port = 5672, 9 UserName = "guest", 10 Password = "guest" 11}; 12 13 using (var connection = factory. createConnection () 14 using (var channel = connection. createModel () 15 {16 channel. exchangeDeclare (exchange: "wen_logs", // switch name 17 type: "fanout"); // switch type 18 19 // create queue 20 var queueName = channel. queueDeclare (). queueName; 21 channel. queueBind (queue: queueName, 22 exchange: "wen_logs", 23 routingKey: ""); 24 25 Console. writeLine ("[*] Waiting for logs. "); 26 27 var consumer = new EventingBasicConsumer (channel); 28 consumer. written ed + = (model, ea) => 29 {30 var body = ea. body; 31 var message = Encoding. UTF8.GetString (body); 32 Console. writeLine ("[x] {0}", message); 33}; 34 channel. basicConsume (queue: queueName, 35 noAck: true, 36 consumer: consumer); 37 38 Console. writeLine ("Press [enter] to exit. "); 39 Console. readLine (); 40} 41} 42}Reciver. cs // recipient
Try to discover-new species EasyNetQ
I just got in touch with RabbitMQ and will not encapsulate it?
Just getting started with RabbitMQ, dare not encapsulate?
I just started RabbitMQ. I don't want to pretend to be familiar with it. I'm afraid someone else will say that you have installed 13?
This is not a problem! EasyNetQ. You can check the name and complete MQ and So easy!
Connect to the RabbitMQ Proxy:
var bus = RabbitHutch.CreateBus("host=localhost");
Release:
bus.Publish(message);
Subscription:
bus.Subscribe<MyMessage>("my_subscription_id", msg => Console.WriteLine(msg.Text));
Let's take a look at the Easy degree through the Demo. Create a project (see the following for Demo download ):
Wen. EasyNetQDemo. Model: Class Library
Wen. EasyNetQDemo. Publisher, Wen. EasyNetQDemo. Subscriber: the console applications are directly installed using Nuget.The EasyNetQ package references the class library Model.
Public class Demo {public string Message {get; set ;}}
Publisher
1 using System; 2 using EasyNetQ; 3 using Wen. easyNetQDemo. model; 4 5 namespace Wen. easyNetQDemo. publisher 6 {7 internal class Program 8 {9 private static void Main (string [] args) 10 {11 using (var bus = rabbithuch. createBus ("host = localhost") 12 {13 string input; 14 Console. writeLine ("enter the information. If it is "esc", it will exit the current window. "); 15 16 while (input = Console. ReadLine ())! = "Esc") 17 {18 bus. Publish (new Demo19 {20 Message = input21}); 22} 23 24} 25} 26} 27}
[Note] the rabbithuch. CreateBus () method can be used to create a simple publish/subscribe message bus that contains the request/response API.
Subscriber
1 using System; 2 using EasyNetQ; 3 using Wen. easyNetQDemo. model; 4 5 namespace Wen. easyNetQDemo. subscriber 6 {7 internal class Program 8 {9 private static void Main (string [] args) 10 {11 using (var bus = rabbithuch. createBus ("host = localhost") 12 {13 bus. subscribe <Demo> ("test", HandleDemo); 14 15 Console. writeLine ("listening information... enter "return" to exit the current window! "); 16 Console. readLine (); 17} 18} 19 20 private static void HandleDemo (Demo demo Demo) 21 {22 Console. foregroundColor = ConsoleColor. green; 23 Console. writeLine ($ "Got message: {demo. message} "); 24 Console. resetColor (); 25} 26} 27}
Figure:
"The world is full of knowledge and human experience, that is, an article 」 [Blogger] Anti-bone Aberdeen [original] http://www.cnblogs.com/liqingwen/p/6412089.html