Due to the company's business needs, recently wanted to RABBITMQ, before I studied Microsoft's MSMQ for some time. There are many open source queues, each with its own merits. First take RABBITMQ practice practiced hand. This article focuses on the Code section, as to how to install, how to configure not repeat. And the code is implemented on the basis of the Rabbitmq.net Client class library.
Suppose the person reading this article has installed RABBITMQ and made the appropriate user configuration. And Rabbitmq.client.dll has been installed in the project from NuGet. We started to do a simple queue to send and receive messages.
- Put what you need to configure in the configuration file, such as host address, port, user name, password, etc.
- Implementing the message sender side: Product
- Implement message receiving end: Customer
- Demo Test
Place the following as a configurable section in the configuration file
<appSettings> <!--rabbitmq--> <add key="Rabbitmq_hosturi"Value="amqp://192.168.1.119:5672/"/> <add key="Rabbitmq_hostname"Value="192.168.1.119"/> <add key="Rabbitmq_username"Value="Test_user"/> <add key="Rabbitmq_password"Value="123456"/> <add key="Rabbitmq_virtualhost"Value="MS_MQ"/> </appSettings>
Because it is just another encapsulation of the RabbitMQ.Client.dll, the code is more than explained, and it is important to note some configuration issues, such as whether to persist, what the message processing pattern is, and so on.
First we create a connection factory:
Publicconnectionfactory createfactory () {if(_factory = =NULL) { Const ushortHeartbeat =0; //Host AddressUri uri =NewUri (Rabbitmqconfig.hosturi); _factory=NewConnectionFactory (); //_factory. HostName = Rabbitmqconfig.hostname; //User name_factory. UserName =Rabbitmqconfig.username; //Password_factory. Password =Rabbitmqconfig.password; //Virtual Host name_factory. VirtualHost =Rabbitmqconfig.virtualhost; //Connection Terminal_factory. Endpoint =NewAmqptcpendpoint (URI); _factory. Requestedheartbeat=Heartbeat; //automatic re-connect_factory. automaticrecoveryenabled =true; } return_factory; }
A simple message to publish: (The Code research is not thorough enough, only basics ~ ~)
Public voidPublish (stringMessagestringQueuename=NULL) { if(QueueName = =NULL) {QueueName=_queuename; } varFactory =RabbitMQFactory.Instance.CreateFactory (); using(varConnection =Factory. CreateConnection ()) {using(varModel =connection. Createmodel ()) {//message persistence to prevent loss ofModel. Queuedeclare (QueueName, Rabbitmqconfig.isdurable,false,false,NULL); varProperties =model. Createbasicproperties (); Properties. Persistent=rabbitmqconfig.isdurable; Properties. DeliveryMode=2; //message conversion to binary varMsgbody =Encoding.UTF8.GetBytes (message); //messages are sent to the queueModel. Basicpublish ("", QueueName, properties, msgbody); } } }
Message Reception:
Public voidconsume () {varFactory =RabbitMQFactory.Instance.CreateFactory (); varConnection =Factory. CreateConnection (); Connection. Connectionshutdown+=Connection_connectionshutdown; Listenchannel=connection. Createmodel (); BOOLAutodeletemessage =false; varQueue = Listenchannel.queuedeclare (_queuename, Rabbitmqconfig.isdurable,false,false,NULL); //fair distribution, do not send more than one message to a worker at the same timeListenchannel.basicqos (0,1,false); //Create event-driven consumer types, and do not consume messages with a dead loop below varConsumer =NewEventingbasicconsumer (Listenchannel); Consumer. Received+=consumer_received; //Consumer NewsListenchannel.basicconsume (_queuename, autodeletemessage, consumer); }
I defined a receivemessagecallback func callback in the customer, which is what the client decides when the client receives the message from the queue.
Public func<stringboolgetset; }
Processing messages:
Private voidConsumer_received (Objectsender, Basicdelivereventargs args) { Try { varBODY =args. Body; varMessage =Encoding.UTF8.GetString (body); //handing message processing to external business BOOLresult =receivemessagecallback (message); if(Result) {if(Listenchannel! =NULL&&!listenchannel.isclosed) {listenchannel.basicack (args. Deliverytag,false); } } Else { } } Catch(Exception ex) {Throwex; } }
The basic code is complete, we write a test, the message is sent to the end:
Static voidMain (string[] args) { varTestqueuename ="Test"; Imessageproduct Product=Newmessageproduct (testqueuename); for(inti =0; I <10000; i++) {Console.WriteLine ("is sending the first"+ i +"message ..."); Product. Publish (the message body"+i); } console.read (); }
Message receiving end: (open multiple ports receive)
Static voidMain (string[] args) {Parallel.For (0, rabbitmqconfig.threadcount, i ={Imessagecustomer Customer=NewMessagecustomer ("Test");
Start listening to customer. Startlistening (); Customer. Receivemessagecallback= Message = = {
The client processes the message (print) Console.WriteLine ("Receiving message:"+message); return true; }; }); Console.read (); }
Open the Send message side:
Open the message receiving end:
So far, the simple test of the RABBITMQ queue is complete, no new knowledge is introduced, basically is the method in the set DLL, but there are a lot of unreasonable places, if really applied to the project, but also need more testing and modification.
Demo Address:https://github.com/fanpan26/RabbitMQ.NETClient
RabbitMQ. NET Client Combat experiments