2

If both the producer and consumer of events/messages are .Net/C# based, I tend to use metadata in the payload in order to be able to deserialised the data into C# POCOs like so:

Data
{
  "X": {
    "a": "bb811ea5-6993-e511-80fc-1458d043a750",
    "b": "ddd",
    "b": "dddd",
    "d": true
  }
  "x1": 1.1234,
  "x2": 2.3456,
  "EventUtcDateTime": "2016-02-16T08:55:38.5103574Z"
}

Metadata
{
  "TimeStamp": "02/16/2016 08:55:37",
  "EventClrTypeName": "Bla.Di.Bla.SomeClass, Bla.Di.Bla, Version=1.0.0.0, Culture=neutral, PublicKeyToken=null"
}

What would be a good solution in situations where the producer is not .Net/C# based?

4

2 回答 2

7

The EventData class contains a property Properties... that allow you to add metadata to the message:

Gets the user properties of the event data that the user explicitly added during send operations.

So to send a event :

var eventHubClient = EventHubClient.CreateFromConnectionString("connectionString", "eventHubName");
var mypoco = new POCO();
// ...

// Get the Json string
var stringBody = JsonConvert.SerializeObject(mypoco);

// Create the event data
var eventData = new EventData(Encoding.UTF8.GetBytes(stringBody));

// Add the event type.
eventData.Properties.Add("EventType", typeof(POCO).Assembly.FullName);

// Send the data.
eventHubClient.Send(eventData);

While receiving your message, you'll get the event type from the metada of the message:

async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
{
    foreach (EventData eventData in messages)
    {
        var jsonBody = Encoding.UTF8.GetString(eventData.GetBytes());

        //Get the event type
        var eventTypeName = (string)eventData.Properties["EventType"];
        var eventType = Type.GetType(eventTypeName);

        // Deserialize the object
        var myPoco = JsonConvert.DeserializeObject(jsonBody, eventType);
    }
}

Otherwise you can get rid of the body type by using a JObject

async Task IEventProcessor.ProcessEventsAsync(PartitionContext context, IEnumerable<EventData> messages)
{
    foreach (EventData eventData in messages)
    {
        var jsonBody = Encoding.UTF8.GetString(eventData.GetBytes());

        // Deserialize the json as a JObject
        var myPoco = JObject.Parse(jsonBody);
        var a = myPoco["X"]["a"];

    }
}
于 2016-03-21T01:41:45.200 回答
2

For me a logical answer would be add a mandatory EventType in any JSON events shared by different context.

Thus EventType should be a mandatory part of the Data rather than the Metadata.

于 2016-02-17T15:06:11.627 回答