【问题标题】:Azure Storage Queue - CloudQueueMessage different typesAzure 存储队列 - CloudQueueMessage 不同类型
【发布时间】:2014-08-23 05:37:23
【问题描述】:

我在 Azure 存储中有一个队列,我希望能够将不同的消息类型添加到队列中并将它们解析为它们的特定类型。

例如。

public class Customer
{
   public Customer()
   {
   }

   public string Name { get; set;}
   public string Email { get; set;}
   public string Address { get; set;}
}

public class Employee
{
   public Employee()
   {
   }

   public string Id { get; set;}
   public string Name { get; set;}
   public string Email { get; set;}
}

我可以将它们序列化为 JSON 并将它们添加到队列中,但是如何在不知道消息类型的情况下将它们反序列化为它们的特定类型?

我如何知道下一条消息是客户还是员工?我可以在消息中添加某种属性说:“这是客户”或“这是员工”...

因为我有一个工作角色,它将在队列中查找消息并根据类型执行特定操作

get message from queue

If message = customer
  do this
else if message = employee
  do that
else 
  do nothing

【问题讨论】:

    标签: azure azure-storage azure-queues azure-storage-queues


    【解决方案1】:

    我在一个项目中做了以下事情。

    将消息类型存储为BrokeredMessage 的属性(其中entity 是我要发送的类):

    var msg = new BrokeredMessage(entity);
    msg.ContentType = entity.GetType().AssemblyQualifiedName;
    myClient.Send(msg);
    

    在接收方,我有这个扩展方法来获取正确类型的消息:

    public static object GetBodyOfType(this BrokeredMessage msg)
    {
        var ofType = Type.GetType(msg.ContentType);
        var method = typeof(BrokeredMessage).GetMethod("GetBody", new Type[] { });
        var generic = method.MakeGenericMethod(ofType);
        return generic.Invoke(msg, null);
    }
    

    然后我的实际接收者会这样做(receivedMessageBrokeredMessage):

    var msg = receivedMessage.GetBodyOfType();
    

    这给了我msg 这是我排队的类型。

    我使用它的模式与您描述的相似。我将命令排队到 ServiceBus,并有一个工作角色来处理它通过命令处理程序接收到的任何命令。到目前为止,它运行良好。

    编辑:我刚刚意识到您提到了存储队列,而上面是我用于服务总线的。希望解决方案能够适用。

    【讨论】:

    • 您的解决方案适用,但他需要创建自己的包装数据类型。包装器可以公开有关消息类型的信息,就像 BrokeredMessage 类型一样。
    【解决方案2】:

    Azure 存储客户端库不提供对反序列化队列消息的显式支持。因此,请检查您为此使用的序列化程序。例如,如果您使用DataContractSerializer,则可以在序列化/反序列化期间使用known types 处理继承。

    【讨论】:

      【解决方案3】:

      我过去是这样做的。我已经将对象的类型作为字符串记录到消息中,然后添加了一些分隔符:# 然后添加了 json-serialised 字符串。

      所以我的消息应该是这样的:

      MyProject.Domain.Model.Product#{'Id':'42','ProductName':'SuperHumanEnchancer'}
      

      在返回的路上,你读取分隔符之前的任何内容并将其视为类型名称。分隔符号后的字符串将是您的 json 序列化字符串。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-01-28
        • 2020-10-15
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2019-08-17
        • 1970-01-01
        相关资源
        最近更新 更多