.net core 下使用 RabbitMQ 消息没有正确路由到队列处理方式错误消息回调 (五)
消息回调
1 public void Producer() 2 { 3 string queueName = "RE_QUEUE"; 4 string exchangeName = "RE_EXCHANGE"; 5 using (var connection = RabbitMQHelper.GetConnection("192.168.3.200", 5671)) 6 { 7 using (var channel = connection.CreateModel()) 8 { 9 // 声明队列 10 channel.QueueDeclare(queueName, false, false, false, null); 11 // 声明交换机[交换机没有绑定队列的情况] 12 //channel.ExchangeDeclare(exchangeName, ExchangeType.Fanout); 13 //channel.QueueBind(queueName, exchangeName, ""); 14 // 声明交换机 15 channel.ExchangeDeclare(exchangeName, ExchangeType.Direct); 16 channel.QueueBind(queueName, exchangeName, "test_direct"); 17 18 string message = "This is Return Model"; 19 var body = Encoding.UTF8.GetBytes(message); 20 // 配置回调 21 channel.BasicReturn += (o, basic) => 22 { 23 var rc = basic.ReplyCode; //消息失败的code 24 var rt = basic.ReplyText; //描述返回原因的文本。 25 var msg = Encoding.UTF8.GetString(basic.Body.Span); //失败消息的内容 26 //在这里我们可能要对这条不可达消息做处理,比如是否重发这条不可达的消息呀,或者这条消息发送到其他的路由中等等 27 System.IO.File.AppendAllText("d:/return.txt", "调用了Return;ReplyCode:" + rc + ";ReplyText:" + rt + ";Body:" + msg+"\r\n"); 28 Console.WriteLine("send message failed,不可达的消息消息监听."); 29 }; 30 31 var properties = channel.CreateBasicProperties(); 32 properties.MessageId = "fdsfdfs"; 33 channel.BasicPublish(exchange: exchangeName, 34 routingKey: "test_direct1", 35 mandatory: true, // 必须设置该参数为true 36 basicProperties: properties, 37 body: body); 38 39 Console.WriteLine(" [x] Sent {0}", message); 40 } 41 } 42 }