C#操作RabbitMQ示例
阿新 • • 發佈:2018-03-25
ack local ref console tst one hang () del
using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text; using System.Threading; namespace RabbitMQ { class Program { static void Main(string[] args) { var type = Console.ReadLine(); if (type == "PRODUCER") {var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "RabbitMQ_Exchange", type: ExchangeType.Direct, durable: true, autoDelete: false, arguments: null); channel.QueueDeclare(queue: "RabbitMQ_Queue", durable: true, exclusive: false, autoDelete: false, arguments: null); channel.QueueBind(queue: "RabbitMQ_Queue", exchange: "RabbitMQ_Exchange", routingKey: "RabbitMQ_RoutingKey", arguments: null); var properties = channel.CreateBasicProperties(); properties.Persistent = true; for (var i = 0; i < 1000; i++) { var message = $"RabbitMQ_Exchange # RabbitMQ_Queue # RabbitMQ_RoutingKey # {i}"; var body = Encoding.UTF8.GetBytes(message); channel.BasicPublish(exchange: "RabbitMQ_Exchange", routingKey: "RabbitMQ_RoutingKey", basicProperties: properties, body: body); Console.WriteLine(" [x] Sent {0}", message); } Console.ReadLine(); } } if (type == "CONSUMER") { var factory = new ConnectionFactory() { HostName = "localhost" }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { channel.ExchangeDeclare(exchange: "RabbitMQ_Exchange", type: ExchangeType.Direct, durable: true, autoDelete: false, arguments: null); channel.QueueDeclare(queue: "RabbitMQ_Queue", durable: true, exclusive: false, autoDelete: false, arguments: null); channel.QueueBind(queue: "RabbitMQ_Queue", exchange: "RabbitMQ_Exchange", routingKey: "RabbitMQ_RoutingKey", arguments: null); channel.BasicQos(prefetchSize: 0, prefetchCount: 1, global: false); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine(" [x] Received {0}", message); Thread.Sleep(2000); Console.WriteLine(" [x] Done"); channel.BasicAck(deliveryTag: ea.DeliveryTag, multiple: false); }; channel.BasicConsume(queue: "RabbitMQ_Queue", autoAck: false, consumer: consumer); Console.ReadLine(); } } } } }
C#操作RabbitMQ示例