向 Azure 事件中心中的事件添加自定义数据

由于事件主要包含一组不透明的字节,因此这些事件的使用者很难就如何处理它们做出明智的决策。 为了允许事件发布者为使用者提供更好的上下文,事件可能还包含自定义元数据,其形式为一组键-值对。 包含元数据的一种常见方案是提供有关事件所包含的数据类型的提示,以便使用者了解其格式,并可以对其进行适当反序列化。

注意

事件中心服务不会使用此元数据,它对事件中心服务没有任何意义;它仅用于在事件发布者和使用者之间进行协调。

以下部分介绍如何使用不同的编程语言将自定义数据添加到事件中。

.NET

var eventBody = new BinaryData("Hello, Event Hubs!");
var eventData = new EventData(eventBody);
eventData.Properties.Add("EventType", "com.microsoft.samples.hello-event");
eventData.Properties.Add("priority", 1);
eventData.Properties.Add("score", 9.0);

有关完整的代码示例,请参阅发布带有自定义元数据的事件

Java

EventData firstEvent = new EventData("EventData Sample 1".getBytes(UTF_8));
firstEvent.getProperties().put("EventType", "com.microsoft.samples.hello-event");
firstEvent.getProperties().put("priority", 1);
firstEvent.getProperties().put("score", 9.0);

有关完整的代码示例,请参阅发布带有自定义元数据的事件

Python

event_data = EventData('Message with properties')
event_data.properties = {'event-type': 'com.microsoft.samples.hello-event', 'priority': 1, "score": 9.0}

有关完整的代码示例,请参阅批量发送带有属性的事件数据

JavaScript

let eventData = { body: "First event", properties: { "event-type": "com.microsoft.samples.hello-event", "priority": 1, "score": 9.0  } };

后续步骤

请参阅以下快速入门和示例。