.net core 下使用 RabbitMQ 交换机备份 (四)
1 public void BackupMethod() 2 { 3 string queueName = "BACKUP_QUEUE"; 4 string exchangeName = "BACKUP_EXCHANGE"; 5 string backupQueue = "BACKUP_QUEUE_D"; 6 string backupExchangeName = "ALTERNATE_EXCHNAGE"; 7 string routeKey = "BACKUP_ROUTEKEY"; 8 using (var connection = RabbitMQHelper.GetConnection("192.168.3.200", 5671)) 9 { 10 using (var channel = connection.CreateModel()) 11 { 12 // 声明交互交换机[指定备份交换机] 13 Dictionary<string, object> argument = new (); 14 argument.Add("alternate-exchange", backupExchangeName); 15 channel.ExchangeDeclare(exchangeName, ExchangeType.Direct, false, false, argument); 16 // 声明备份交互机 17 channel.ExchangeDeclare(backupExchangeName, ExchangeType.Fanout, false, false, null); 18 // 声明队列 19 channel.QueueDeclare(queueName, false, false, false, null); 20 // 声明备份队列 21 channel.QueueDeclare(backupQueue, false, false, false, null); 22 23 // 绑定队列 24 channel.QueueBind(queueName, exchangeName, routeKey); 25 channel.QueueBind(backupQueue, backupExchangeName, ""); 26 27 //发送数据 28 for (int i = 0; i < 10; i++) 29 { 30 // 消息内容 31 string message = "This is Backup Exchange Model-->"+i; 32 var body = Encoding.UTF8.GetBytes(message); 33 //指定发送消息到哪个路由,以及他的路由键,消息等 34 if (i % 2 == 0) 35 { 36 channel.BasicPublish(exchangeName, routeKey, null, body); 37 } 38 else 39 { 40 //匹配不到队列[如果路由key找不到队列则启用备用交换机] 41 channel.BasicPublish(exchangeName, "kkkk", null, body); 42 } 43 Console.WriteLine(" [x] Sent '" + message + "'"); 44 Thread.Sleep(200); 45 } 46 } 47 } 48 }