適用于 JavaScript 的 AzureCommunicationRoutingService REST 用戶端程式庫
Azure 通訊路由服務
請高度依賴 我們的 REST 用戶端檔 來使用此程式庫
重要連結:
開始使用
目前支援的環境
- Node.js 的 LTS 版本
必要條件
- 您必須有 Azure 訂 用帳戶才能使用此套件。
擁有 ACS 資源
在 Azure 入口網站 中建立 ACS 資源,或使用現有的資源。
安裝 @azure-rest/communication-job-router
套件
使用 npm
安裝適用于 JavaScript 的 AzureCommunicationRoutingService REST 用戶端 REST 用戶端程式庫:
npm install @azure-rest/communication-job-router
建立和驗證 AzureCommunicationRoutingServiceClient
若要使用 Azure Active Directory (AAD) 權杖認證,請提供從 @azure/身分識別 程式庫取得所需認證類型的實例。
若要向 AAD 進行驗證,您必須先 npm
安裝 @azure/identity
安裝之後,您可以選擇 要使用的認證@azure/identity
類型。
例如, DefaultAzureCredential 可用來驗證用戶端。
將 AAD 應用程式的用戶端識別碼、租使用者識別碼和用戶端密碼的值設定為環境變數:AZURE_CLIENT_ID、AZURE_TENANT_ID、AZURE_CLIENT_SECRET
教學課程:使用 Azure 通訊服務 (ACS) 作業路由器 Rest SDK 將作業路由傳送至背景工作
在本教學課程中,您將了解:
- 如何建立佇列。
- 如何建立背景工作角色,並將其指派給佇列。
- 如何將作業路由傳送至背景工作。
- 如何訂閱及處理作業路由器事件。
- 如何完成和關閉作業。
啟動 NodeJS Express 伺服器
在殼層 (cmd、PowerShell、Bash 等 ) 中,建立名為 RouterQuickStart
的資料夾,並在此資料夾內執行 npx express-generator
。 這會產生會接聽 的 port 3000
簡單 Express 專案。
範例
mkdir RouterQuickStart
cd RouterQuickStart
npx express-generator
npm install
DEBUG=routerquickstart:* npm start
安裝 Azure ACS 作業路由器 SDK
在 RouterQuickStart
資料夾中,執行 npm install @azure-rest/communication-job-router --save
來安裝 ACS 作業路由器 SDK。
路由作業
建構 AzureCommunicationRoutingServiceClient
首先,我們需要建構 AzureCommunicationRoutingServiceClient
。
const JobRouterClient = require("@azure-rest/communication-job-router").default;
const connectionString = "endpoint=https://<YOUR_ACS>.communication.azure.com/;accesskey=<YOUR_ACCESS_KEY>";
const routerClient = JobRouterClient(connectionString);
建立散發原則
此原則會決定哪些背景工作會接收作業供應專案,因為工作會分散到其佇列中。
const distributionPolicy = await routerClient.path("/routing/distributionPolicies/{id}", "distributionPolicy-1").patch({
contentType: "application/merge-patch+json",
body: {
name: "distribution-policy-123",
offerExpiresAfterSeconds: 30,
mode: {
kind: "longestIdle",
minConcurrentOffers: 1,
maxConcurrentOffers: 3,
},
}
});
建立佇列
此佇列會根據我們先前建立的散發原則,為背景工作提供工作。
const salesQueueId = "queue-123";
await routerClient.path("/routing/queues/{id}", salesQueueId).patch({
contentType: "application/merge-patch+json",
body: {
distributionPolicyId: distributionPolicy.body.id,
name: "Main",
labels: {},
}
});
建立背景工作角色
這些背景工作角色會指派給我們先前建立的「銷售」佇列,並具有一些標籤。
- 設定
availableForOffers
為true
表示這些工作者已準備好接受作業供應專案。 - 請參閱我們的 標籤檔 ,以進一步瞭解標籤和標籤選取器。
// Create worker "Alice".
const workerAliceId = "773accfb-476e-42f9-a202-b211b41a4ea4";
const workerAliceResponse = await routerClient.path("/routing/workers/{workerId}", workerAliceId).patch({
contentType: "application/merge-patch+json",
body: {
capacity: 120,
queues: [salesQueueId],
labels: {
Xbox: 5,
german: 4,
name: "Alice"
},
channels: [
{
channelId: "CustomChatChannel",
capacityCostPerJob: 10,
},
{
channelId: "CustomVoiceChannel",
capacityCostPerJob: 100,
},
],
}
});
// Create worker "Bob".
const workerBobId = "21837c88-6967-4078-86b9-1207821a8392";
const workerBobResponse = await routerClient.path("/routing/workers/{workerId}", workerBobId).patch({
contentType: "application/merge-patch+json",
body: {
capacity: 100,
queues: [salesQueueId],
labels: {
Xbox: 5,
english: 3,
name: "Alice"
},
channels: [
{
channelId: "CustomChatChannel",
capacityCostPerJob: 10,
},
{
channelId: "CustomVoiceChannel",
capacityCostPerJob: 100,
},
],
}
});
作業生命週期
請參閱我們的 作業生命週期檔 ,以進一步瞭解作業的生命週期。
建立作業
此作業會加入我們先前建立的「銷售」佇列。
const jobId = "router-job-123";
const result = await routerClient.path("/routing/jobs/{id}", jobId).patch({
contentType: "application/merge-patch+json",
body: {
channelReference: "66e4362e-aad5-4d71-bb51-448672ebf492",
channelId: "voice",
priority: 2,
queueId: "salesQueueId",
labels: {},
}
});
(選擇性) 使用分類原則建立作業
建立分類原則
此原則會在建立時分類作業。
- 請參閱我們的 規則檔 ,以進一步瞭解優先順序規則。
const classificationPolicyId = "classification-policy-123";
const result = await routerClient.path("/routing/classificationPolicies/{id}", classificationPolicyId).patch({
contentType: "application/merge-patch+json",
body: {
name: "Default Classification Policy",
fallbackQueueId: salesQueueId,
queueSelectorAttachments: [
{
kind: "static",
queueSelector: { key: "department", labelOperator: "equal", value: "xbox" }
},
],
workerSelectorAttachments: [{
kind: "static",
workerSelector: { key: "english", labelOperator: "greaterThan", value: 5 }
}],
prioritizationRule: {
kind: "expression",
language: "powerFx",
expression: "If(job.department = \"xbox\", 2, 1)"
}
}
});
建立和分類作業
此作業將會使用我們先前建立的分類原則進行分類。 它也具有標籤。
const result = await routerClient.path("/routing/jobs/{id}", jobId).patch({
contentType: "application/merge-patch+json",
body: {
channelReference: "66e4362e-aad5-4d71-bb51-448672ebf492",
channelId: "voice",
classificationPolicyId: classificationPolicy.id,
labels: {
department: "xbox"
},
}
});
``
## Events
Job Router events are delivered via Azure Event Grid. Refer to our [Azure Event Grid documentation](/azure/event-grid/overview) to better understand Azure Event Grid.
In the previous example:
- The job gets enqueued to the “Sales" queue.
- A worker is selected to handle the job, a job offer is issued to that worker, and a `RouterWorkerOfferIssued` event is sent via Azure Event Grid.
Example `RouterWorkerOfferIssued` JSON shape:
```json
{
"id": "1027db4a-17fe-4a7f-ae67-276c3120a29f",
"topic": "/subscriptions/{subscription-id}/resourceGroups/{group-name}/providers/Microsoft.Communication/communicationServices/{communication-services-resource-name}",
"subject": "worker/{worker-id}/job/{job-id}",
"data": {
"workerId": "w100",
"jobId": "7f1df17b-570b-4ae5-9cf5-fe6ff64cc712",
"channelReference": "test-abc",
"channelId": "FooVoiceChannelId",
"queueId": "625fec06-ab81-4e60-b780-f364ed96ade1",
"offerId": "525fec06-ab81-4e60-b780-f364ed96ade1",
"offerTimeUtc": "2023-08-17T02:43:30.3847144Z",
"expiryTimeUtc": "2023-08-17T02:44:30.3847674Z",
"jobPriority": 5,
"jobLabels": {
"Locale": "en-us",
"Segment": "Enterprise",
"Token": "FooToken"
},
"jobTags": {
"Locale": "en-us",
"Segment": "Enterprise",
"Token": "FooToken"
}
},
"eventType": "Microsoft.Communication.RouterWorkerOfferIssued",
"dataVersion": "1.0",
"metadataVersion": "1",
"eventTime": "2023-08-17T00:55:25.1736293Z"
}
訂閱事件
訂閱 ACS 作業路由器事件的其中一種方式是透過 Azure 入口網站。
- 在 Azure 入口網站中流覽至您的 ACS 資源,然後開啟 [事件] 刀鋒視窗。
- 新增 「RouterWorkerOfferIssued」 事件的事件訂用帳戶。
- 選取適當的方法來接收事件 (,例如 Webhook、Azure Functions、服務匯流排) 。
請參閱我們的 「訂閱作業路由器事件」檔 ,以進一步瞭解訂閱作業路由器事件。
接收事件的 NodeJS 應用程式中的路由看起來可能會像這樣:
app.post('/event', (req, res) => {
req.body.forEach(eventGridEvent => {
// Deserialize the event data into the appropriate type
if (eventGridEvent.eventType === "Microsoft.EventGrid.SubscriptionValidationEvent") {
res.send({ validationResponse: eventGridEvent.data.validationCode });
} else if (eventGridEvent.eventType === "Microsoft.Azure.CommunicationServices.RouterWorkerOfferIssued") {
// RouterWorkerOfferIssued handling logic;
} else if ...
});
...
});
接受或拒絕作業供應專案
收到 RouterWorkerOfferIssued
事件後,您可以接受或拒絕作業供應專案。
workerid
- 接受作業供應專案的背景工作識別碼。offerId
- 要接受或拒絕之供應專案的識別碼。
const acceptResponse = await routerClient.path("/routing/workers/{workerId}/offers/{offerId}:accept", workerId, offerId).post();
// or
const declineResponse = await routerClient.path("/routing/workers/{workerId}/offers/{offerId}:decline", workerId, offerId).post();
完成作業
assignmentId
需要從上一個步驟的回應接收,才能完成作業。
const completeJob = await routerClient.path("/routing/jobs/{id}/assignments/{assignmentId}:complete", jobId, acceptResponse.body.assignmentId).post({
body: {
note: `Job has been completed by ${workerId} at ${new Date()}`
}
});
關閉作業
一旦背景工作完成作業的包裝階段, jobRouterClient
就可以關閉作業,並將處置程式碼附加至該作業以供日後參考。
const closeJob = await routerClient.path("/routing/jobs/{id}/assignments/{assignmentId}:close", jobId, acceptResponse.body.assignmentId).post({
body: {
note: `Job has been closed by ${workerId} at ${new Date()}`
}
});
疑難排解
記錄
啟用記錄有助於找出失敗的相關實用資訊。 若要查看 HTTP 的要求和回應記錄,請將 AZURE_LOG_LEVEL
環境變數設定為 info
。 或者,您可以在 @azure/logger
中呼叫 setLogLevel
,以在執行階段啟用記錄:
const { setLogLevel } = require("@azure/logger");
setLogLevel("info");
如需如何啟用記錄的詳細指示,可參閱 @azure/logger 套件文件。