生产者:
static void Main(string[] args)
{
IConnectionFactory factory = new ConnectionFactory//创建连接工厂对象
{
HostName = "192.168.1.16",//IP地址
Port = 5672,//端口号
UserName = "sean",//用户账号
Password = "sean"//用户密码
};
using (IConnection con = factory.CreateConnection())
{
using (IModel channel = con.CreateModel())
{
//string queueName = "test";
//channel.ExchangeDeclare(exchange:"logs",type:"fanout",durable:true,autoDelete:false);
channel.ExchangeDeclare(exchange: "direct_logs", type: "direct", durable: true, autoDelete: false);
//channel.QueueDeclare(
// queue: queueName,
// durable:true,
// exclusive: false,
// autoDelete: false
// );
List
list1.Add("asd");
list1.Add("xc");
list1.Add("zxvvzx");
list1.Add("ad");
list1.Add("fg");
foreach(var item in list1)
{
Console.WriteLine("请输入routing key:");
string name = Console.ReadLine();
byte[] body = Encoding.UTF8.GetBytes(item);
//消息持久化
var props = channel.CreateBasicProperties();
props.Persistent = true;
channel.BasicPublish(exchange: "direct_logs", routingKey: name, basicProperties: props, body: body);
}
}
}
Console.WriteLine("send over!");
}
消费者:
static void Main(string[] args)
{
Console.WriteLine("Start");
Console.WriteLine("请输入queue_name/routing_key:");
string name = Console.ReadLine();
string routingname = Console.ReadLine();
IConnectionFactory factory = new ConnectionFactory//创建连接工厂对象
{
HostName = "192.168.1.16",//IP地址
Port = 5672,//端口号
UserName = "sean",//用户账号
Password = "sean"//用户密码
};
//创建连接
var connection = factory.CreateConnection();
//创建通道
var channel = connection.CreateModel();
//声明队列
channel.QueueDeclare(queue: name, durable:true,exclusive:false,autoDelete:false);
channel.QueueBind(queue:name, exchange:"direct_logs", routingKey: routingname, null);
//能者多劳模式
channel.BasicQos(prefetchSize:0,prefetchCount:1,global:false);
//事件基本消费者
EventingBasicConsumer consumer = new EventingBasicConsumer(channel);
//接收到消息事件
consumer.Received += (ch, ea) =>
{
var message = Encoding.UTF8.GetString(ea.Body.ToArray());
testaa(message);
//确认该消息已经被消费
channel.BasicAck(ea.DeliveryTag, false);
//
Console.WriteLine($"已发送回执[{ea.DeliveryTag}]");
};
//启动消费者 设置为手动应答消息
channel.BasicConsume(name, false, consumer);
Console.WriteLine("消费者已启动");
Console.ReadKey();
channel.Dispose();
connection.Close();
}
public static void testaa(string message)
{
Thread.Sleep((message.Length)*1000);
Console.WriteLine("receive:" + message);
}