简体   繁体   English

C#Rabbitmq序列化消息并反序列化原始类型

[英]C# Rabbitmq serialize message and desiralize original type

I am using Rabbitmq client to produce and consume messages. 我正在使用Rabbitmq客户端生成和使用消息。 My messages is like this. 我的信息就是这样。

public interface IMessage{}

public class PlaceOrder: IMessage{ 
  public string id{ get; set; }
}    

I have two c# console applicaiton projects. 我有两个c#控制台应用程序项目。 One of them Producer and other is Consumer . 消费者生产者中的一个,其他是生产者

Producer console applicaiton 生产者控制台应用程序

public class Producer{
    public void Save(IMessage message){
        ....
        var serializedObject = JsonConvert.SerializeObject(message);
        ....
        // append queue serializedObject 
    }
}

Consumer console applicaiton 消费者控制台应用

public class Consumer{
    public void HandleBasicDeliver(string consumerTag, ulong deliveryTag, bool redelivered, string exchange, string routingKey, IBasicProperties properties, byte[] body){
        ....
        var message = JsonConvert.DeserializeObject(Encoding.UTF8.GetString(body));
        ....

    }
}

Here message type is Object. 这里的message类型是对象。 And consumer console applicaiton does not knows PlaceOrder type. 消费者控制台应用程序不知道PlaceOrder类型。 It only knows IMessage interface type. 它只知道IMessage接口类型。 How can I cast or convert original type. 如何转换或转换原始类型。

Look at the options in NewtonSoft.Json's TypeNameHandling enumeration . 查看NewtonSoft.Json的TypeNameHandling枚举中的选项。 Set this on a JsonSerializerSettings and pass it into your calls to De/SerializeObject() . JsonSerializerSettings上进行设置 ,并将其传递到对De/SerializeObject()调用中。

You may also want to evaluate EasyNetQ , which is specifically geared to this approach out-of-box, and adds other functionality. 您可能还需要评估EasyNetQ ,它特别适用于此方法,并添加了其他功能。

Note there can be some disadvantages (architecturally) to insisting that message producers and consumers always use identically-named types with identical message structures. 请注意,坚持要求消息生产者和使用者始终使用具有相同消息结构的名称相同的类型(在体系结构上)可能会有一些缺点。 You can end up tightly coupling all producers and consumers, such that all must be deployed in lock-step when a message format changes (as opposed to adopting a Tolerant Reader approach, which can allow for more loosely-coupled evolution of producers and consumers). 您最终可能会紧密耦合所有生产者和使用者,因此,当消息格式发生更改时,所有程序都必须以锁步方式进行部署(与采用“允许阅读器”方法相对,后者可以使生产者和使用者之间的耦合更为松散) 。 Depends on your project goals, but an aspect to consider. 取决于您的项目目标,但要考虑的一个方面。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM