rabbitmq is not described as and how to install it. Baidu knows it at once, just pay more attention in terms of configuration.
Without further ado, let’s start with a simple example code
Sender:
ConnectionFactory factory = new ConnectionFactory { HostName = "hostname", UserName = "root", Password = "root001", VirtualHost = "hostserver" }; using (IConnection conn = factory.CreateConnection()) { using (IModel im = conn.CreateModel()) { im.ExchangeDeclare("rabbitmq_route", ExchangeType.Direct); im.QueueDeclare("rabbitmq_query", false, false, false, null); im.QueueBind("rabbitmq_query", "rabbitmq_route", ExchangeType.Direct, null); for (int i = 0; i < 1000; i++) { byte[] message = Encoding.UTF8.GetBytes("Hello Lv"); im.BasicPublish("rabbitmq_route", ExchangeType.Direct, null, message); Console.WriteLine("send:" + i); } } }
Receiver:
ConnectionFactory factory = new ConnectionFactory { HostName = "hostname", UserName = "root", Password = "root001", VirtualHost = "hostserver" }; using (IConnection conn = factory.CreateConnection()) { using (IModel im = conn.CreateModel()) { while (true) { BasicGetResult res = im.BasicGet("rabbitmq_query", true); if (res != null) { Console.WriteLine("receiver:"+UTF8Encoding.UTF8.GetString(res.Body)); } } } }
Send a thousand sending one at one time, the sending process is fast, and it is relatively slow when receiving.
Just end it.
It can be seen that when two receivers are running at the same time, RabbitMQ will Distribute each message sequentially. When each confirmation is received, the message will be deleted, and then the next one will be distributed to the next recipient, mainly because of RabbitMQ's
cyclic distributionmechanism.
. When multiple receivers, due to the reasons of cycle distribution, the news is almost two receiving end. So how to distribute the same message to multiple receivers.Modify the sending terminal code:
##
ConnectionFactory factory = new ConnectionFactory { HostName = "hostname", UserName = "root", Password = "root001", VirtualHost = "host" }; using (IConnection conn = factory.CreateConnection()) { using (IModel im = conn.CreateModel()) { im.ExchangeDeclare("rabbitmq_route_Fanout", ExchangeType.Fanout);// 路由 int i = 0; while (true) { Thread.Sleep(1000); ++i; byte[] message = Encoding.UTF8.GetBytes(i.ToString()); im.BasicPublish("rabbitmq_route_Fanout", "", null, message); Console.WriteLine("send:" + i.ToString()); } } }
# When a new receiving end connection (consumer), you need to declare a new queue, Comment on code 1. When RabbitMQ declares a queue, it will automatically generate one if you do not specify a name, which is good.
What are the disadvantages? You will know after running it yourself.
The above is the detailed content of Detailed explanation of graphic code for RabbitMQ application in C#. For more information, please follow other related articles on the PHP Chinese website!