RabbitMQ is simple to use in C,

Source: Internet
Author: User
Tags rabbitmq

RabbitMQ is simple to use in C,

What RabbitMQ is and how to install it will not be described in detail, Baidu will know at a glance, but pay more attention to configuration.

Let's not talk about it. First, let's go directly to a simple sample code (the following code is only a simple DEMO ):

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);                    }                }            }

 

Acceptor:

            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));                        }                    }                }            }

The sender sends one thousand messages at a time. The sending process is fast and the receiving process is relatively slow.

Next, modify the code to bring the Code closer to the actual application.

The above DEMO only supports one receiver, which has the same sending volume. If there are multiple receivers, add a new receiver and directly copy the receiver in the DEMO.

Attached running result:

As you can see, when both receivers run simultaneously, RabbitMQ distributes each message in order. After each confirmation is received, the message is deleted and then distributed to the next receiver, mainly because ofCyclic DistributionMechanism.

As mentioned above, when multiple receivers are involved, messages are almost divided by two receivers due to cyclic distribution.

How to distribute the same message to multiple receivers.

Modify the sender 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); // route 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 ());}}}

Compared with the previous method, you will find that there are two less sections of code after the code comment. After setting the Fanout mode, you do not need to specify the queue name. One second is stopped to make it easy to view the results, so as not to refresh too quickly.

Let's take a look at the acceptor 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);                    var queueOk = im.QueueDeclare();//1                    im.QueueBind(queueOk.QueueName, "rabbitmq_route_Fanout", "");//2                    var consumer = new QueueingBasicConsumer(im);//3                    im.BasicConsume(queueOk.QueueName, true, consumer);//4                    while (true)                    {var _result = (BasicDeliverEventArgs)consumer.Queue.Dequeue();//5                        var body = _result.Body;                        var message = Encoding.UTF8.GetString(body);                        Console.WriteLine("received:{0}", message);                    }                }            

When a new receiver is connected (the Consumer), a new queue is required to be declared. Note 1 of the Code. When RabbitMQ declares a queue, a new queue is automatically generated if no name is specified, this is good.

The results are run on both receivers as expected.

If there is something wrong with the broadcast method, you can run it yourself.

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.