RabbitMQ Original article 02 -- "Hello Word ",
All the articles in this series are from the original articles on the official website and belong to personal translators. If there are similar articles, you can archive them and try again.
. NET/C # RabbitMQ client: https://github.com/rabbitmq/rabbitmq-dotnet-client
For more information about RabbitMQ installation and management configuration on windows, see: http://www.cnblogs.com/grayguo/p/5300776.html
Make sure the installation is successful:
This part will write two programs, one producer sends one message, and one consumer accepts the message and then outputs it to the console. In this process, I will ignore some messages. net details, focus on this simple "hello word" message program.
"P" is our producer, "C" is our consumer, and the middle is our message queue-a message buffer hidden behind the consumer.
Send:
Create a Send. cs program to write the sending program. The sender connects to the RabbitMQ server, sends the message, and then exits.
class Send{ public static void Main() { var factory = new ConnectionFactory() { HostName = "192.168.15.128" }; using (var connection = factory.CreateConnection()) { using (var channel = connection.CreateModel()) { ... } } }}
First, create a connection factory to connect to our RabbitMQ server. Here we use the class library provided by RabbitMQ-dotnet-client to create a session.
The connection here has already done socket connection, version protocol, and authentication session for us. here, the server I connect to is "192.168.15.128" (because I have planted the RabbitMQ test environment on a virtual machine, if it is a local machine, it can be written as "localhost"), you can directly specify the Server IP address.
Then we create a session on this connection. Most of the Api operations we do are performed based on sessions.
To send a message, we need to create a queue to store the message. Then we can send our message to this queue and create the queue code:
Channel. queueDeclare (queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); // queue: Team name // durable: persistence/exclusive: exclusive/autoDelete: automatic deletion
Note: The APIs used to create a queue are idempotent, that is, they are created only when the specified queue does not exist.
Then send the message:
string message = "Hello World!"; var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "",routingKey: "hello", basicProperties: null, body: body);
The sent message must be a byte array. We can specify the required encoding.
The complete code is as follows:
Public class Send {public static void Main () {var factory = new ConnectionFactory () {HostName = "192.168.15.128"}; using (var connection = factory. createConnection () using (var channel = connection. createModel () {channel. queueDeclare (queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); string message = "Hello World! "; Var body = Encoding. UTF8.GetBytes (message); channel. basicPublish (exchange: "", routingKey: "hello", basicProperties: null, body: body); Console. writeLine ("[x] Sent {0}", message);} Console. writeLine ("Press [enter] to exit. "); Console. readLine ();}}View Code
Run the code and you can see the result through the client management tool.
We can see that the queue named "hello" is created, and a message is stored in the queue once.
Note: Normally, our messages can only arrive at the Queue after being routed through the switch (exchange). The Queue is created and then directly (exchange and Queue are not manually bound) when we create a queue, rabbitMQ will automatically bind the newly created queue and RoutingKey to the queue name to a switch with the default name.
Receive messages
RabbitMQ will actively push messages to our message recipients. Unlike the message senders who send a single message, we will allow the message recipients to continuously listen for messages and print them out.
Create a Receive. cs to write the code for receiving messages.
class Receive { private static void Main(string[] args) { var factory = new ConnectionFactory() { HostName = "192.168.15.128" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.QueueDeclare(queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); } } }
The initial code and Send. cs is basically a line. It creates a connection and creates a session. Here, the queue named "hello" is created to prevent the client from starting first, the target queue for the request cannot be found.
After connecting to the server, we told RabbitMQ to actively push the message to us. Because RabbitMQ pushes the message asynchronously (asynchronously), we use EventingBasicConsumer. Received to accept the message.
Var consumer = new EventingBasicConsumer (channel );
Consumer. stored ed + = (model, ea) =>{ var body = ea. body; var message = Encoding. UTF8.GetString (body); Console. writeLine ("[x] Received {0}", message) ;}; channel. basicConsume (queue: "hello", noAck: true, consumer: consumer );
// NoAck: Concept of ack: After a Consumer receives a message and processes a task, it sends an ack with the message identifier to tell the server that the message has been received and processed, if no, the server will.
// If it is set to true, the Consumer will return ack immediately after receiving the message
// Set to false: manually send the message. No, RabbitMQ determines that the message is not correctly processed until the Consumer link for processing the message is lost, so that RabbitMQ resends the message.
The complete code is as follows:
Class Receive {private static void Main (string [] args) {var factory = new ConnectionFactory () {HostName = "192.168.15.128"}; using (var connection = factory. createConnection () using (var channel = connection. createModel () {channel. queueDeclare (queue: "hello", durable: false, exclusive: false, autoDelete: false, arguments: null); var consumer = new EventingBasicConsumer (channel); consumer. stored ed + = (model, ea) =>{ var body = ea. body; var message = Encoding. UTF8.GetString (body); Console. writeLine ("[x] Received {0}", message) ;}; channel. basicConsume (queue: "hello", noAck: true, consumer: consumer); Console. writeLine ("Press [enter] to exit. "); Console. readLine ();}}}View Code
Run the code Send:
Sent successfully.
Run the code Reveive:
The message is successfully received.