RabbitMQ使用交换机处理异步消息队列案例
RabbitMQ使用交换机处理异步消息队列案例的安装环境可以参考 RabbitMQ环境准备/环境搭建,
本片在RabbitMQ环境已有的基础上讲述RabbitMQ使用交换机处理异步消息队列具体过程
1、新建.NET Core console控制台项目ConsoleRabbitMQ项目(生产者 productor,即产生消息的)以及ConsoleRabbitMQ01项目(consumer消费者,即使用消息的)
2、对控制台项目使用NuGet程序管理包添加RabbitMQ.Client
3、控制台项目ConsoleRabbitMQ项目的Program代码如下
using RabbitMQ.Client; using System; namespace ConsoleRabbitMQ { class Program { static void Main(string[] args) { Console.WriteLine("RabbitMQ 生产者开始。。。生产。。。!"); #region RabbitMQ 生产者 var connectionFactory = new ConnectionFactory() { HostName = "localhost", UserName = "guest", Password = "guest" }; using (var connection = connectionFactory.CreateConnection()) { using var channel = connection.CreateModel(); channel.QueueDeclare("myqueue", true, false, false, null); channel.ExchangeDeclare("myexchange", ExchangeType.Direct, true, false, null); channel.QueueBind("myqueue", "myexchange", "myexchangekey", null); for (int i = 0; i < 100; i++) { var body = System.Text.Encoding.UTF8.GetBytes($"这是发布的数据。{i}。"); channel.BasicPublish("myexchange", "myexchangekey", null, body); System.Threading.Thread.Sleep(TimeSpan.FromSeconds(1)); } } #endregion Console.WriteLine("RabbitMQ 输入任何字符退出。。"); Console.Read(); } } }
4、控制台项目ConsoleRabbitMQ01项目的Program代码如下
using RabbitMQ.Client; using System; using RabbitMQ.Client.Events; namespace ConsoleRabbitMQ01 { class Program { static void Main(string[] args) { Console.WriteLine("RabbitMQ 消费者开始。。。消费。。。!"); #region RabbitMQ 消费者 var connectionFactory = new ConnectionFactory() { HostName = "localhost", UserName = "guest", Password = "guest" }; using (var connection = connectionFactory.CreateConnection()) { using var channel = connection.CreateModel(); channel.QueueDeclare("myqueue", true, false, false, null); channel.ExchangeDeclare("myexchange", ExchangeType.Direct, true, false, null); channel.QueueBind("myqueue", "myexchange", "myexchangekey", null); var received = new EventingBasicConsumer(channel); received.Received += (sender, e) => { //手动确认,正常消费,通知消息中心,该条消息可以删除了 //channel.BasicAck(e.DeliveryTag, false); var body = System.Text.Encoding.UTF8.GetString(e.Body.ToArray()); channel.BasicConsume("myqueue", true, received); }; } #endregion Console.WriteLine("RabbitMQ 输入任何字符退出。。"); Console.Read(); } private static void Received_Received(object sender, BasicDeliverEventArgs e) { throw new NotImplementedException(); } } }
5、启动RabbitMQ服务,输入命令:rabbitmq-service start
6、分别启动ConsoleRabbitMQ.exe和ConsoleRabbitMQ01.exe这个两个项目
浏览器中输入:http://localhost:15672/#/,点击Connections,Channels,Queues可以查看相关信息