First, the program uses Netcore, the introduction of NuGet:
Install-Package RabbitMQ.Client -Version 4.1.3
Second, the end of the message:
usingrabbitmq.client;usingSystem;usingSystem.Text;namespaceclientdemo{ Public classClient {Static stringExchangename ="My-exchange"; Static stringQueueName ="My-queue"; Public Static voidMain () {console.inputencoding=Encoding.unicode; Console.outputencoding=Encoding.unicode; ConnectionFactory Factory=NewConnectionFactory (); Factory. Uri=NewUri ("Amqp://guest:[email protected]:5672/"); varconn =Factory. CreateConnection (); IModel Model=Conn. Createmodel (); //model. Exchangedelete (exchangename);Model. Exchangedeclare (Exchange:exchangename, Type:ExchangeType.Direct, durable:false, Autodelete:false, arguments:NULL); Model. Queuedeclare (queue:queuename, durable:true, Exclusive:false, Autodelete:false, arguments:NULL); Model. Queuebind (Queue:queuename, Exchange:exchangename, routingkey:queuename); varProps =model. Createbasicproperties (); Props. Persistent=true;//is persisted while(true) {Console.WriteLine ("Please enter a message to send:"); varline =Console.ReadLine (); if(line = ="Exit") Break; Model. Basicpublish (Exchange:exchangename, Routingkey:queuename, Basicproperties:props, Body:Encoding.UTF8.GetBytes (line )); } model. Close (); Conn. Close (); } }}
Second, the consumer end of the message:
usingrabbitmq.client;usingSystem;usingSystem.Text;usingSystem.Threading;usingSystem.Threading.Tasks;namespaceserverdemo{ Public classServer {//static string exchangename = "My-exchange"; Static stringQueueName ="My-queue"; Public Static voidMain () {console.inputencoding=Encoding.unicode; Console.outputencoding=Encoding.unicode; ConnectionFactory Factory=NewConnectionFactory (); //Factory. URI = new Uri ("AMQP://guest:[email protected]:5672/"); varconn =Factory. CreateConnection (); IModel Model=Conn. Createmodel (); //model. Exchangedeclare (Exchange:exchangename, Type:ExchangeType.Direct, Durable:false, Autodelete:false, arguments:null); //model. Queuedeclare (Queue:queuename, Durable:true, Exclusive:false, Autodelete:false, arguments:null); //model. Queuebind (Queue:queuename, Exchange:exchangename, routingkey:queuename); varTask = Task.run (() = { while(true) { varresult = model. Basicget (Queue:queuename, Autoack:false); if(Result = =NULL) {Thread.Sleep (Ten);Continue; }; varmsg =Encoding.UTF8.GetString (result. Body); Console.WriteLine (msg); } }); Task. Wait (); Model. Close (); Conn. Close (); } }}
Using RABBITMQ to send and receive queue messages in C #