【问题标题】:How should I pass a string value in a RabbitMQ header我应该如何在 RabbitMQ 标头中传递字符串值
【发布时间】:2021-11-07 22:29:30
【问题描述】:

我正在尝试将字符串值添加到 RabbitMQ 消息中。

当我在此处撰写消息时,代码如下:

IBasicProperties props = channel.CreateBasicProperties();
props.ContentType = "text/plain";
props.DeliveryMode = 2;
props.Expiration = "36000000";
props.Headers = new Dictionary<string, object>();
props.Headers.Add("entityId", id);
props.Headers.Add("type", GetMessageType(id));

channel.BasicPublish(exchange: "messages",
    routingKey: "",
    basicProperties: props,
    body: body);

方法GetMessageType返回一个字符串。

我这样检索消息:

private void ConsumerOnReceived(object sender, BasicDeliverEventArgs e)
{
    var firstMessage = "PO Received";
    var secondMessage = "Do you want to print a Back Order Fill Report?";
    
    var id = (int) e.BasicProperties.Headers.FirstOrDefault(x => x.Key == "entityId").Value;
    string type;
    try
    {
        type = (string)e.BasicProperties.Headers.FirstOrDefault(x => x.Key == "type").Value;
    }
    catch (Exception exception)
    {
        Console.WriteLine(exception);
        throw;
    }
    
    if (type == "OrderCreated")
    {
        firstMessage = "Sales Order Created";
        secondMessage = "Do you want to print the Order?";
    }
    ...

第一个标头值 (entityId) 可以正常检索。第二个(类型)导致异常。

异常消息:Message = "Unable to cast object of type 'System.Byte[]' to type 'System.String'."

我需要将字节数组转换回字符串吗?还是应该只传递整数?

如果我需要将字节数组转换回字符串,我该怎么做?

【问题讨论】:

    标签: c# rabbitmq


    【解决方案1】:

    这是由于 RMQ 协议更新为 0-9-1 时的一个旧怪癖。基本上引入了线级不一致,这种行为允许发送字节数组和字符串头(两者都发送如S 长字符串类型)。

    请参阅https://github.com/rabbitmq/rabbitmq-dotnet-client/issues/415,了解数据类型信息丢失的原因;该链接还包括一种关于如何读取字符串标题的方法。

    string json;
    //We set this as a string, but deliveries will return a UTF8-encoded byte[]..
    if (value.GetType() == typeof(byte[]))
    {
      json = Encoding.UTF8.GetString((byte[])value);
    }
    

    当然,这也可能意味着原始标头是一个字节数组。

    【讨论】:

      【解决方案2】:

      我找到了答案:

      type = System.Text.Encoding.UTF8.GetString((byte[])e.BasicProperties.Headers.FirstOrDefault(x => x.Key == "type").Value);
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-12-09
        • 2019-04-29
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-04-30
        • 2018-06-22
        • 1970-01-01
        相关资源
        最近更新 更多