1.生产者:
using RabbitMQ.Client; using System; using System.Text; namespace Publisher1 { class Program { static void Main(string[] args) { ConnectionFactory factory = new ConnectionFactory() { HostName = "127.0.0.1", UserName = "mytest", Password = "mytest" }; //第一步:创建connection var connection = factory.CreateConnection(); //第二步:创建channel var channel = connection.CreateModel(); //第三步:申明交换机 //第四步:声明一个队列 channel.QueueDeclare("manQueue", true, false, false, null); //循环往队列中插入100条数据 for (int i = 1; i <= 100; i++) { var msg = Encoding.UTF8.GetBytes($"{i}:希望!"); //第五步:发布消息 channel.BasicPublish(string.Empty, routingKey: "manQueue", basicProperties: null, body: msg); } Console.WriteLine("完成"); } } }
2.消费者
using RabbitMQ.Client; using RabbitMQ.Client.Events; using System; using System.Text; namespace Consumer1 { class Program { static void Main(string[] args) { ConnectionFactory factory = new ConnectionFactory() { HostName = "127.0.0.1", UserName = "mytest", Password = "mytest" }; //第一步:创建connection var connection = factory.CreateConnection(); //第二步:创建channel var channel = connection.CreateModel(); //第三步:申明交换机 channel.QueueDeclare("manQueue", true, false, false, null); //第四步:获取消息 //BasicGet是主动获取 这里要使用发布订阅模式 //var result = channel.BasicGet("manQueue", true); //var msg = Encoding.UTF8.GetString(result.Body); EventingBasicConsumer consumer = new EventingBasicConsumer(channel); consumer.Received += (sender,e)=> { var msg = Encoding.UTF8.GetString(e.Body); Console.WriteLine(msg); }; //第五步 要指出 去订阅哪个队列 用哪个消费者 channel.BasicConsume("manQueue", true, consumer); Console.ReadKey(); } } }
3.如果要使用自定义的交换机 不用默认的交换机
using RabbitMQ.Client; using System; using System.Text; namespace Publisher1 { class Program { static void Main(string[] args) { ConnectionFactory factory = new ConnectionFactory() { HostName = "127.0.0.1", UserName = "mytest", Password = "mytest" }; //第一步:创建connection var connection = factory.CreateConnection(); //第二步:创建channel var channel = connection.CreateModel(); //第三步:申明交换机 channel.ExchangeDeclare("MyExchange",ExchangeType.Direct,true,false,null); //由于不是默认的交换机 所以还要跟队列做一个绑定 channel.QueueBind("manQueue", "MyExchange", "manQueue", null); //第四步:声明一个队列 channel.QueueDeclare("manQueue", true, false, false, null); //循环往队列中插入100条数据 for (int i = 1; i <= 100; i++) { var msg = Encoding.UTF8.GetBytes($"{i}:希望!"); //第五步:发布消息 //这时候要使用指定的交换机 //channel.BasicPublish(string.Empty, routingKey: "manQueue", basicProperties: null, body: msg); channel.BasicPublish("MyExchange", routingKey: "manQueue", basicProperties: null, body: msg); } Console.WriteLine("完成"); } } }