【问题标题】:RabbitMQ not throwing error on invalid routing keyRabbitMQ 不会在无效的路由键上抛出错误
【发布时间】:2017-02-24 22:01:57
【问题描述】:

我在C#中有以下代码,如果路由键无效,它不会抛出错误。

var connFactory = GetConnectionFactory();

using (var conn = connFactory.CreateConnection())
{
    using (var channel = conn.CreateModel())
    {
        channel.TxSelect();

        var publicationAddress = new PublicationAddress(ExchangeType.Direct, Settings.ServiceBusExchange, Settings.ServiceBusRoutingKey);

        var headers = new Dictionary<String, Object>();
        headers.Add("TransactionID", transactionID);

        var basicProperties = new BasicProperties();
        basicProperties.ContentEncoding = Encoding.UTF8.ToString();
        basicProperties.ContentType = "text/xml";
        basicProperties.Headers = headers;
        basicProperties.DeliveryMode = 2;

        var payLoad = Encoding.UTF8.GetBytes(message);

        channel.BasicPublish(publicationAddress, basicProperties, payLoad);
        channel.TxCommit();
    }
}

我的问题是,如果路由键无效,如何使代码抛出错误?就像当我使用带有无效路由密钥的 RabbitMQ UI 发布消息时,它会给出一条消息“消息已发布,但未路由。”

提前致谢。

【问题讨论】:

    标签: c# rabbitmq rabbitmq-exchange


    【解决方案1】:

    它不存在“无效路由键”的概念,因为您可以将队列动态绑定到交换器。

    顺便说一句,您正在寻找的是“不可路由的消息”,您必须使用mandatory 标志并在同一通道中实现ReturnListener,如果消息没有到达任何队列,则将被重定向到处理程序。 就这样(代码是Java,但在c#中差不多):

     boolean isMandatory = true; // if true the message will be handled by HandlingReturnListener
            // if false the message will be dropped!
    
            channel.addReturnListener(new ReturnListener() {
                public void handleReturn(int replyCode, String replyText, String exchange, String routingKey, AMQP.BasicProperties properties, byte[] body) throws IOException {
                    System.out.println(replyText + ":" + replyCode);
                    System.out.println("********  UnHandled Message ***************");
    
                }
    
            });
    
            String myExchange = "myUnroutableExchange_";
            channel.exchangeDeclare(myExchange, "topic", false, false, null);
            channel.basicPublish(myExchange, "NO_KEY", isMandatory, null, "".getBytes());
    

    【讨论】:

      【解决方案2】:

      为此,有一个叫做 PublisherAcknoledgement 的东西。这基本上会给发布者一个关于消息状态的确认。您还可以区分消息是到达 Exchange 还是到达消费者。您只需要正确处理每个案例。

      这是了解正在传递的消息状态的好方法。您可能不知道它是否由于错误的路由键而发生,但通过进行各种检查,您可能能够缩小结果范围。

      【讨论】:

      • Publish Confirm 确认消息到达服务器而不是队列。
      猜你喜欢
      • 1970-01-01
      • 2016-06-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2019-04-25
      • 1970-01-01
      • 2017-10-17
      • 2014-08-21
      相关资源
      最近更新 更多