1.首先要安装 RabbitMQ Client
2.创建一个控制台项目 取名 Publisher代码如下:
using RabbitMQ.Client; using System; using System.Text; namespace Publisher { 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); var msg = Encoding.UTF8.GetBytes("希望!"); //第五步:发布消息 channel.BasicPublish(string.Empty, routingKey: "manQueue", basicProperties: null, body: msg); Console.WriteLine("完成"); } } }
3.创建一个控制台项目 取名 Consumer代码如下:
using RabbitMQ.Client; using System; using System.Text; namespace Consumer { 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(); //第三步:申明交换机 //第四步:获取消息 var result = channel.BasicGet("manQueue", true); var msg = Encoding.UTF8.GetString(result.Body); Console.WriteLine(msg); } } }