. NET file concurrency and RABBITMQ (preliminary RABBITMQ)

Source: Internet
Author: User
Tags rabbitmq

The copyright of this article belongs to the blog park and the author Wu Di himself together. Welcome reprint, Reprint and crawler Please specify the original address: http://www.cnblogs.com/tdws/p/5860668.html

Presumably MQ these two letters are not unfamiliar to seniors and old drivers. In this paper, the simple sharing of RABBITMQ may be worth learning is not much, I rabbitmq research is also very elementary, this month intends to follow a good learning line to improve, welcome new and old drivers leave your opinion.

First it mentions the first simple scenario, the file concurrency. I first manually implement the file concurrency, throw an exception, see the following code.

1 Static voidMain (string[] args)2         {3             NewThread (write1). Start ();4             NewThread (write1). Start ();5             NewThread (write1). Start ();6Console.WriteLine ("wait");7 Console.readkey ();8         }9          Public Static voidwrite1 ()Ten         { One              for(inti =0; I <10000; i++) A             { - Writelog (i); -             } the             //Console.readkey (); -         } -          Public Static voidWritelog (inti) -         { +             using(FileStream f =NewFileStream (@"D:\\a.txt", filemode.append)) -             { +                 using(StreamWriter SW =NewStreamWriter (F, encoding.default)) A                 { atSw. Write (i); -                 } -             } -}

I use multithreaded concurrency to the same append data. Believe you should know what will happen next!

Yes, as you expected, the file is being used by another process, so the process cannot access the file. Maybe this scenario, just like you write application run log, Exception Log. If you do not use any plugins or components, you can only append them directly to the file. The problem is that you have to solve it.

This is the time for the queue to appear. Of course there are a lot of components in the queue. NET Framework also has its own queue, Microsoft also has a separate queue component Msqueue. Apache has its activemq, the other well-known message queue also has EQUEUE,ZEROMQ and so on. Message Queuing usage scenarios, presumably including decoupling, improved peak processing power, delivery and sequencing guarantees, buffering, etc.

RABBITMQ is a message-oriented middleware whose main point of view is simple: to accept and forward messages. You can think of him as a post office, and when you send new to the mail box, you're pretty sure that the postman will eventually pass your new build to your recipient's hands. We use mail boxes and postman to metaphor RABBITMQ. The main difference between RABBITMQ and the post office is that the post Office handles paper letters, while MQ stores and forwards binary data-message. Here are some of the "jargon" of RABBITMQ.

A producer means sending a message. An application that sends a message is a producer, which we call "P".

Queues queue means the mail box. He exists in the midst of RABBITMQ. Although messages are "circulating" in RABBITMQ and your application, they can be in only one queue. A queue is free of any restrictions, and he can store the amount of messages you want to store, which is essentially an infinite buffer. Multiple producers can send messages to the same queue, and multiple consumers can try to receive data from the same message queue. A queue like this, above is its queue name.

Consumers are meant to receive, and consumers are the applications waiting to receive processing messages.

The final relationship is as follows:

Next, I'll use RABBITMQ to solve the first file concurrency problem. That is, to avoid file concurrency, we need to store the content of the producer's append into the message queue, and then take the message from the queue and let the consumer write to the file. About the installation and configuration of the RABBITMQ please read the Zhang Shanyu Teacher's article: http://www.cnblogs.com/shanyou/p/4067250.html, written in particular detail. Just a few months RABBITMQ the C # client method has a slight update.

Below I will create a new two ConsoleApp application. A responsible receive, consumer, write file. Another send, producer, pushes the data needed to write to the RABBITMQ.

The receive code is as follows:

 Static voidMain (string[] args) {            varFactory =NewConnectionFactory () {HostName ="", UserName ="Wushuang", Password ="123456" }; using(varConnection =Factory. CreateConnection ())using(varChannel =connection. Createmodel ()) {channel. Queuedeclare (Queue:"Hello", Durable:false, Exclusive:false, Autodelete:false, arguments:NULL); varConsumer =NewEventingbasicconsumer (channel); Consumer. Received+ = (model, ea) = =                {                    varBODY =ea.                    Body; varMessage =Encoding.UTF8.GetString (body);                Writelog (message);                }; Channel. Basicconsume (Queue:"Hello", Noack:true, Consumer:consumer); Console.WriteLine ("Press [Enter] to exit.");            Console.ReadLine (); }        }         Public Static voidWritelog (stringi) {using(FileStream f =NewFileStream (@"D:\\a.txt", Filemode.append)) {                using(StreamWriter SW =NewStreamWriter (F, Encoding.default)) {SW. Write (i+"\ n"); }            }        }

The send code is as follows:

Static voidMain (string[] args) {            NewThread (write1).            Start (); NewThread (write1).            Start (); NewThread (write1).            Start (); Console.WriteLine ("Press [Enter] to exit.");        Console.ReadLine (); }         Public Static voidwrite1 () {varFactory =NewConnectionFactory () {HostName ="", UserName ="Wushuang", Password ="123456" }; using(varConnection =Factory. CreateConnection ())using(varChannel =connection. Createmodel ()) {channel. Queuedeclare (Queue:"Hello", Durable:false, Exclusive:false, Autodelete:false, arguments:NULL); Channel. Queuebind ("Hello","Wsexchange","Hello");  for(inti =0; I <10000; i++)                {                    stringMessage ="Hello World ws!"+i; varBODY =Encoding.UTF8.GetBytes (message); Channel. Basicpublish (Exchange:"Wsexchange", Routingkey:"Hello", Basicproperties:NULL, Body:body); Console.WriteLine ("[x] Sent {0}", message); }            }                       //Console.readkey ();}

With the code, you first run the receive project. Waits for the producer to send the message to the queue, and then the event that the receive subscription will take out the message and write the message to the file.

The ConsoleApp on the left continues to write messages to the queue, and the ConsoleApp on the right side of the receive will continue to write the file during the run. The producer is subjected to multi-threaded concurrency of some data, of course, the consumer ordered to take out the queue of data, and will not occur the first file concurrency exception.

Today's share is so simple, about RABBITMQ to continue in-depth study.

If you feel my little share, to you a bit of help, welcome to praise, but also for your own progress to praise!

Reference article:

Zhang Shanyu Teacher: Install RABBITMQ Guide on Windows

RabbitMQ (open source) Official document Hello World

. NET file concurrency and RABBITMQ (preliminary RABBITMQ)

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.