Azure 架構登錄是 Azure 事件中樞所裝載的架構存放庫服務,提供架構記憶體、版本控制和管理。 此套件提供 Json 串行化程式,能夠串行化和還原串行化包含 Json 串行化數據的承載。
主要連結:
開始
先決條件
- Azure 訂用帳戶
- 現有的 架構登錄資源
安裝 @azure/schema-registry-json 套件
使用 npm安裝適用於 JavaScript 的 Azure 文字分析用戶端連結庫:
npm install @azure/schema-registry-json
重要概念
JsonSchemaSerializer
提供 API,以串行化至包含架構標識碼的內容類型欄位,並從包裝在訊息中的 JSON 還原串行化。 使用來自 @azure/schema-registry 套件的 SchemaRegistryClient,從架構定義取得架構標識符,反之亦然。 提供的 API 具有內部快取,以避免盡可能呼叫架構登錄服務。
消息
根據預設,串行化程式會建立結構化的訊息,如下所示:
data:包含 JSON 數據的位元組陣列。contentType:下列格式的字串application/json+<Schema ID>,其中application/json元件會發出此訊息具有 Json 串行化承載的訊號,而<Schema Id>部分則是指派給架構登錄服務用來串行化此承載的架構標識符。
並非所有傳訊服務都支援相同的訊息結構。 若要啟用與這類服務的整合,串行化程式可以使用對應的訊息產生者和取用者,在建構函式中設定 messageAdapter 選項,以處理自定義訊息結構。 Azure 傳訊用戶端連結庫會匯出其訊息類型的預設配接器。
例子
串行化和還原串行化 @azure/event-hubs的 EventData
const { DefaultAzureCredential } = require("@azure/identity");
const { createEventDataAdapter } = require("@azure/event-hubs");
const { SchemaRegistryClient } = require("@azure/schema-registry");
const { JsonSchemaSerializer } = require("@azure/schema-registry-json");
async function main(){
const client = new SchemaRegistryClient(
"<fully qualified namespace>",
new DefaultAzureCredential()
);
const serializer = new JsonSchemaSerializer(client, {
groupName: "<group>",
messageAdapter: createEventDataAdapter(),
});
// Example Json schema
const schema = JSON.stringify({
$schema: "http://json-schema.org/draft-04/schema#",
$id: "person",
title: "Student",
description: "A student in the class",
type: "object",
properties: {
name: {
type: "string",
description: "The name of the student",
},
},
required: ["name"]
});
// Example value that matches the Json schema above
const value = { name: "Bob" };
// Serialize value to a message
const message = await serializer.serialize(value, schema);
// Deserialize a message to value
const deserializedValue = await serializer.deserialize(message);
}
main().catch((err) => {
console.error("The sample encountered an error:", err);
});
串行化程式不會檢查還原串行化值是否符合架構,但提供實作這類驗證的選項。 應用程式可以將驗證回呼函式當做其中一個選項傳遞至可實作架構驗證的還原串行化方法。
若要查看驗證的實作方式,請參閱 schemaRegistryJsonWithValidation 範例。
故障排除
Json 串行化程式會視需要與 架構登錄 服務通訊,而這些服務呼叫可能會擲回 RestError。 此外,串行化或還原串行化失敗時,將會擲回類型 Error 的錯誤。
cause 屬性會包含從 JSON 剖析器擲回的基礎錯誤。
伐木
啟用記錄可能有助於找出有關失敗的實用資訊。 若要查看 HTTP 要求和回應的記錄,請將 AZURE_LOG_LEVEL 環境變數設定為 info。 或者,您可以在運行時間啟用記錄,方法是在 @azure/logger中呼叫 setLogLevel:
const { setLogLevel } = require("@azure/logger");
setLogLevel("info");
後續步驟
如需如何使用此連結庫的詳細範例,請參閱 範例 目錄。
貢獻
此項目歡迎參與和建議。 大部分的捐款都要求您同意「參與者許可協定」(CLA),宣告您有權,而且實際上確實會授與我們使用您貢獻的許可權。 如需詳細資訊,請瀏覽 https://cla.microsoft.com。
當您提交提取要求時,CLA-Bot 會自動判斷您是否需要提供 CLA 並適當裝飾 PR(例如標籤、批註)。 只要遵循 Bot 所提供的指示即可。 您只需要使用我們的 CLA 在所有存放庫上執行此動作一次。
此專案已採用 Microsoft開放原始碼。 如需詳細資訊,請參閱 《行為規範》常見問題 或連絡 opencode@microsoft.com,以取得任何其他問題或意見。
如果您想要參與此連結庫,請閱讀 參與指南,以深入瞭解如何建置和測試程序代碼。
相關專案