我应该如何在 RabbitMQ header 中传递字符串值

How should I pass a string value in a RabbitMQ header

我正在尝试将字符串值添加到 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);

方法GetMessageTypereturns一个字符串。

我这样检索消息:

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?";
    }
    ...

第一个 header 值 (entityId) 检索得很好。第二个(类型)导致异常。

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

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

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

我找到了答案:

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

这是由于 RMQ 协议更新为 0-9-1 时的一个老怪癖。基本上引入了 wire-level 不一致,这种行为允许发送字节数组和字符串 header(两者都作为 S long-string 类型发送)。

有关数据类型信息丢失原因的讨论,请参阅 https://github.com/rabbitmq/rabbitmq-dotnet-client/issues/415; link 还包括一种关于如何读取字符串 headers.

的方法
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);
}

当然,这也可能意味着原来的header是一个字节数组。