(1)、引入依赖
RabbitMQ.Client
(2)、编写发布者代码
var connectionFactory = new ConnectionFactory() { HostName="192.168.205.128",UserName="guest",Password="guest"}; //创建连接工厂
var connection = connectionFactory.CreateConnection(); //创建connection
var channel = connection.CreateModel(); //创建channel
//声明交换机
//String exchange, 交换机名称
//String type, 交换机类型
//Boolean durable, 是否持久化
//Boolean autoDelete, 是否自动删除
//IDictionary< String, Object > arguments 交换机参数
channel.ExchangeDeclare("netExchange", ExchangeType.Direct, true, false, null);
//声明队列
//String queue, 队列名称
//Boolean durable, 是否持久化
//Boolean exclusive, 是否专有的(排外)
//Boolean autoDelete, 是否自动删除
//IDictionary<String, Object> arguments 队列参数
channel.QueueDeclare("netQueue", true, false, false, null);
//将队列绑定到交换机上
//String queue, 队列名称
//String exchange, 交换机名称
//String routingKey, routingKey
//IDictionary< String, Object > arguments 绑定参数
channel.QueueBind("netQueue", "netExchange", "netMessage", null);
//发布消息
//String exchange, 交换机名称
//String routingKey, routingKey
//IBasicProperties basicProperties, 发布属性
//Byte[] body 消息内容
channel.BasicPublish("netExchange", "netMessage", null, Encoding.UTF8.GetBytes("来自.net的问候"));
Console.ReadKey();
(3)、编写消费者代码
var connectionFactory = new ConnectionFactory() { HostName = "192.168.205.128", UserName = "guest", Password = "guest" }; //创建连接工厂
var connection = connectionFactory.CreateConnection(); //创建connection
var channel = connection.CreateModel(); //创建channel
//声明交换机
//String exchange, 交换机名称
//String type, 交换机类型
//Boolean durable, 是否持久化
//Boolean autoDelete, 是否自动删除
//IDictionary< String, Object > arguments 交换机参数
channel.ExchangeDeclare("netExchange", ExchangeType.Direct, true, false, null);
//声明队列
//String queue, 队列名称
//Boolean durable, 是否持久化
//Boolean exclusive, 是否专有的(排外)
//Boolean autoDelete, 是否自动删除
//IDictionary<String, Object> arguments 队列参数
channel.QueueDeclare("netQueue", true, false, false, null);
//将队列绑定到交换机上
//String queue, 队列名称
//String exchange, 交换机名称
//String routingKey, routingKey
//IDictionary< String, Object > arguments 绑定参数
channel.QueueBind("netQueue", "netExchange", "netMessage", null);
//1.直接获取消息
//var result = channel.BasicGet("netQueue", true);
//Console.WriteLine(Encoding.UTF8.GetString(result.Body));
//2.使用事件机制获取消息
EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
consumer.Received += (sender, e) =>
{
Console.WriteLine(Encoding.UTF8.GetString(e.Body));
};
channel.BasicConsume("netQueue", true, consumer);
Console.ReadKey();