1、通过Nuget 获取Rabbit MQ NET client bindings from NuGet:
PM> Install-Package RabbitMQ.Client
2、发送者(生产者)代码:
public class RabbitMqSender { private static string strHostName = "localhost"; private static string strExchangeName = "test.exchange.1"; private static string strQueueName = "test.queue.1"; private static string strRouteKey = "test.exchange.key.1"; public static void send() { var factory = new ConnectionFactory() { HostName= strHostName }; using (var connection=factory.CreateConnection()) { using (var channel=connection.CreateModel()) { //channel.QueueDeclare // (queue: strQueueName, // durable: true, // exclusive: false, // autoDelete: false, // arguments: null // ); //channel.ExchangeDeclare(exchange: strQueueName,type:"direct", durable: true, autoDelete: false, arguments: null); channel.ExchangeDeclare(strExchangeName, ExchangeType.Direct, true, false); channel.QueueDeclare(strQueueName, true, false, false, null); channel.QueueBind(strQueueName, strExchangeName, strRouteKey, null); string message = string.Empty; byte[] body = null; for (int i = 0; i < 10; i++) { message = i+DateTime.Now.ToString() + " -----send rabbitmq message!"; body = Encoding.UTF8.GetBytes(message); channel.BasicPublish( exchange: strExchangeName, routingKey: strRouteKey, basicProperties: null, body: body ); Console.WriteLine("{0}", message); } } } } }
3、接收者(消费者)代码
public class RabbitMqReceiver { private static string strHostName = "localhost"; private static string strExchangeName = "test.exchange.1"; private static string strQueueName = "test.queue.1"; private static string strRouteKey = "test.exchange.key.1"; public static void receive() { var factory = new ConnectionFactory() { HostName = strHostName }; using (var connection = factory.CreateConnection()) using (var channel = connection.CreateModel()) { //channel.ExchangeDeclare(exchange: strQueueName, type: "direct", durable: true, autoDelete: false, arguments: null); channel.ExchangeDeclare(strExchangeName, ExchangeType.Direct, true, false); channel.QueueDeclare(strQueueName, true, false, false, null); channel.QueueBind(strQueueName, strExchangeName, strRouteKey, null); var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, ea) => { var body = ea.Body; var message = Encoding.UTF8.GetString(body); Console.WriteLine("AAAAAAAAA--- [x] Received {0}", message); }; channel.BasicConsume(queue: strQueueName, noAck: true, consumer: consumer); //BasicGetResult result = channel.BasicGet(queue: "test.queue", noAck: true); //while (result!= null) //{ // string strMessage = Encoding.UTF8.GetString(result.Body); // Console.WriteLine(" [x] Received {0}", strMessage); // result = channel.BasicGet(queue: "test.queue", noAck: true); //} Console.WriteLine(" Press [enter] to exit."); Console.ReadLine(); } } }
4、运行效果