标签:view false create sum oca 通道 console icc 账号
简单模式中有一个生产者一个消费者,这里分别是SimpleServer,SimpleClient.SimpleServer作为生产者,给队列发送消息,而SimpleClient作为消费者去消费消息。每条消息都是消费完就没了。
static void Main(string[] args) { //1.创建连接工厂 ConnectionFactory factory = new ConnectionFactory() { HostName = "127.0.0.1", UserName = "guest", Password = "guest" }; //2.创建连接 var connection = factory.CreateConnection(); //3.创建管道 var channel = connection.CreateModel(); //4.声明队列 channel.QueueDeclare("simple", false, false, false, null); string msg = "这是一条消息"; var sendByte = Encoding.UTF8.GetBytes(msg); //5.发布消息 channel.BasicPublish("", "simple", null, sendByte); channel.Close(); connection.Close(); }
static void Main(string[] args) { //初始化工厂 ConnectionFactory factory = new ConnectionFactory() { HostName = "127.0.0.1", UserName = "guest", Password = "guest" }; //创建连接 using (IConnection connection = factory.CreateConnection()) { using (IModel channel = connection.CreateModel()) { //声明队列 channel.QueueDeclare("simple", false, false, false, null); //创建消费者对象 var consumer = new EventingBasicConsumer(channel); consumer.Received += (model, e) => { byte[] message = e.Body.ToArray(); Console.WriteLine("接收消息:" + Encoding.UTF8.GetString(message)); //返回消息确认 channel.BasicAck(e.DeliveryTag, false); }; //消费者开启监听 channel.BasicConsume("simple", false, consumer); Console.ReadLine(); } } }
我们先改下生产者发布消息的代码,发布10条消息
for (int i = 0; i < 10; i++) { string msg = $"第{i+1}条消息"; //5.发布消息 channel.BasicPublish("", "simple", null, Encoding.UTF8.GetBytes(msg)); Console.WriteLine($"已发送消息:{msg}"); }
现在我们打开本地RabbitMQ管理后台 http://localhost:15672/
启动SimpleServer程序发布消息后出现十条记录:
开始消费消息:
消费后simple队列里的消息从10条变成了0条。
本篇到这就完结了,下一篇工作队列模式
标签:view false create sum oca 通道 console icc 账号
原文地址:https://www.cnblogs.com/zousc/p/12725453.html