Azure Service Bus 는 Microsoft의 매우 안정적인 클라우드 메시징 서비스입니다.
응용 프로그램의 클라이언트 라이브러리를 @azure/service-bus 사용하여 다음을 수행할 수 있습니다.
- Azure Service Bus 큐 또는 토픽에 메시지 보내기
- Azure Service Bus 큐 또는 구독에서 메시지 받기
- Azure Service Bus 네임스페이스에서 큐/주제/구독/규칙을 만들고/가져오고/삭제하고/업데이트하고, 나열합니다.
버전 7의 @azure/service-bus 리소스:
키 링크:
참고: 버전 1.1.10 이하를 사용 중이고 이 패키지의 최신 버전으로 마이그레이션하려는 경우 마이그레이션 가이드를 참조하여 Service Bus V1에서 Service Bus V7로 이동하세요.
시작하기
패키지 설치
npm을 사용하여 Azure Service Bus 클라이언트 라이브러리의 최신 버전을 설치합니다.
npm install @azure/service-bus
현재 지원되는 환경
Prerequisites
TypeScript 구성
TypeScript 사용자는 노드 형식 정의를 설치해야 합니다.
npm install @types/node
또한 tsconfig.jsoncompilerOptions.allowSyntheticDefaultImports 사용하도록 설정해야 합니다.
compilerOptions.esModuleInterop사용하도록 설정한 경우 기본적으로 allowSyntheticDefaultImports 사용하도록 설정됩니다. 자세한 내용은 TypeScript의 컴파일러 옵션 핸드북 참조하세요.
JavaScript 번들
브라우저에서 이 클라이언트 라이브러리를 사용하려면 먼저 번들러를 사용해야 합니다. 이 작업을 수행하는 방법에 대한 자세한 내용은 번들링 설명서참조하세요.
여기에 설명된 내용 외에도 이 라이브러리는 브라우저에서 제대로 작동하려면 다음 NodeJS 코어 내장 모듈에 대한 추가 폴리필이 필요합니다.
bufferospathprocess
Webpack과 번들링
Webpack v5를 사용하는 경우 다음 개발 종속성을 설치할 수 있습니다
npm install --save-dev os-browserify path-browserify
그런 다음 webpack.config.js에 다음을 추가하십시오.
const path = require("path");
+const webpack = require("webpack");
module.exports = {
entry: "./src/index.ts",
@@ -12,8 +13,21 @@ module.exports = {
},
],
},
+ plugins: [
+ new webpack.ProvidePlugin({
+ process: "process/browser",
+ }),
+ new webpack.ProvidePlugin({
+ Buffer: ["buffer", "Buffer"],
+ }),
+ ],
resolve: {
extensions: [".ts", ".js"],
+ fallback: {
+ buffer: require.resolve("buffer/"),
+ os: require.resolve("os-browserify"),
+ path: require.resolve("path-browserify"),
+ },
},
롤업과 번들링
롤업 번들러를 사용하는 경우 다음 개발 종속성을 설치합니다
npm install --save-dev @rollup/plugin-commonjs @rollup/plugin-inject @rollup/plugin-node-resolve
그런 다음 rollup.config.js에 다음을 포함하십시오.
+import nodeResolve from "@rollup/plugin-node-resolve";
+import cjs from "@rollup/plugin-commonjs";
+import shim from "rollup-plugin-shim";
+import inject from "@rollup/plugin-inject";
export default {
// other configs
plugins: [
+ shim({
+ fs: `export default {}`,
+ net: `export default {}`,
+ tls: `export default {}`,
+ path: `export default {}`,
+ dns: `export function resolve() { }`,
+ }),
+ nodeResolve({
+ mainFields: ["module", "browser"],
+ preferBuiltins: false,
+ }),
+ cjs(),
+ inject({
+ modules: {
+ Buffer: ["buffer", "Buffer"],
+ process: "process",
+ },
+ exclude: ["./**/package.json"],
+ }),
]
};
폴리필 사용에 대한 자세한 내용은 즐겨 사용하는 번들러의 설명서를 참조하십시오.
React Native 지원
브라우저와 마찬가지로 React Native는 이 SDK 라이브러리에서 사용하는 일부 JavaScript API를 지원하지 않으므로 폴리필을 제공해야 합니다. 자세한 내용은 Expo를 사용한 Messaging React Native 샘플을 참조하세요.
클라이언트 인증
Service Bus와의 상호 작용은 ServiceBusClient 클래스의 인스턴스로 시작됩니다. 연결 문자열을 사용하거나 Azure Active Directory 자격 증명을 사용하여 Service Bus에 인증할 수 있습니다.
연결 문자열 사용
이 메서드는 연결 문자열을 Service Bus 인스턴스로 가져옵니다. Azure Portal에서 연결 문자열을 가져올 수 있습니다.
import { ServiceBusClient } from "@azure/service-bus";
const serviceBusClient = new ServiceBusClient("<connectionString>");
이 생성자에 대한 자세한 내용은 API 설명서에서 확인할 수 있습니다.
Azure Active Directory 자격 증명 사용
Azure Active Directory를 사용한 인증은 Azure ID 라이브러리를 사용합니다.
아래 예제에서는 라이브러리에서 사용 가능한 여러 자격 증명 공급자 중 하나인 DefaultAzureCredential을 @azure/identity 사용합니다.
import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";
const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
참고: AAD에
TokenCredential대해 인터페이스의 고유한 구현을 사용하는 경우 service-bus의 "범위"를 다음으로 설정하여 적절한 토큰을 가져옵니다.
["https://servicebus.azure.net//user_impersonation"];
이 생성자에 대한 자세한 내용은 API 설명서에서 확인할 수 있습니다
주요 컨셉
를 초기화 ServiceBusClient하면 Service Bus 네임스페이스 내에서 이러한 리소스와 상호 작용할 수 있습니다.
- 큐: 메시지를 보내고 받을 수 있습니다. 지점 간 통신에 자주 사용됩니다.
- 주제: 큐와 달리 주제는 게시/구독 시나리오에 더 적합합니다. 토픽을 보낼 수 있지만 구독이 필요하며, 그 중 여러 개가 병렬로 사용할 수 있습니다.
- 구독: 토픽에서 사용하는 메커니즘입니다. 각 구독은 독립적이며 주제로 전송된 각 메시지의 사본을 받습니다. 규칙 및 필터를 사용하여 특정 구독에서 수신하는 메시지를 조정할 수 있습니다.
이러한 리소스에 대한 자세한 내용은 Azure Service Bus란?을 참조하세요.
이러한 리소스와 상호 작용하려면 다음 SDK 개념에 익숙해야 합니다.
- 생성된 using
ServiceBusSender를 사용하여ServiceBusClient.createSender()큐 또는 주제로 메시지를 보냅니다. - 큐 또는 구독에서 created using
ServiceBusReceiver를 사용하여ServiceBusClient.createReceiver()메시지를 받습니다. - 세션 사용 큐 또는 구독에서 생성된 using
ServiceBusSessionReceiver또는ServiceBusClient.acceptSession()를 사용하여ServiceBusClient.acceptNextSession()메시지를 받습니다.
Queues, Topics 및 Subscriptions는 이 라이브러리를 사용하기 전에 생성해야 합니다.
Examples
다음 섹션에서는 Azure Service Bus를 사용하는 일반적인 작업 중 일부를 다루는 코드 조각을 제공합니다
- 메시지 보내기
- 메시지 수신
- 메시지 정산
- 배달 못한 편지 큐
- 세션을 사용하여 메시지 보내기
- 세션에서 메시지 받기
- 리스트 메시지 세션
- Service Bus 네임스페이스의 리소스 관리
- 추가 샘플
메시지 보내기
클래스의 인스턴스를 ServiceBusClient 생성하면 메시지를 ServiceBusSender 데 사용할 수 있는 createSender 메소드를 사용할 수 있습니다.
import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";
const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
const sender = serviceBusClient.createSender("my-queue");
const messages = [
{ body: "Albert Einstein" },
{ body: "Werner Heisenberg" },
{ body: "Marie Curie" },
{ body: "Steven Hawking" },
{ body: "Isaac Newton" },
{ body: "Niels Bohr" },
{ body: "Michael Faraday" },
{ body: "Galileo Galilei" },
{ body: "Johannes Kepler" },
{ body: "Nikolaus Kopernikus" },
];
// sending a single message
await sender.sendMessages(messages[0]);
// sending multiple messages in a single call
// this will fail if the messages cannot fit in a batch
await sender.sendMessages(messages);
// Sends multiple messages using one or more ServiceBusMessageBatch objects as required
let batch = await sender.createMessageBatch();
for (let i = 0; i < messages.length; i++) {
const message = messages[i];
if (!batch.tryAddMessage(message)) {
// Send the current batch as it is full and create a new one
await sender.sendMessages(batch);
batch = await sender.createMessageBatch();
if (!batch.tryAddMessage(messages[i])) {
throw new Error("Message too big to fit in a batch");
}
}
}
// Send the batch
await sender.sendMessages(batch);
메시지 받기
클래스의 인스턴스를 ServiceBusClient 생성하면 ServiceBusReceiver 메소드를 사용하여 얻을 수 있습니다.
import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";
const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
const receiver = serviceBusClient.createReceiver("my-queue");
두 가지 receiveModeS를 사용할 수 있습니다.
- "peekLock" - peekLock 모드에서 수신자는 큐에 지정된 기간 동안 메시지를 잠급니다.
- "receiveAndDelete" - receiveAndDelete 모드에서는 메시지가 수신될 때 Service Bus에서 삭제됩니다.
receiveMode가 옵션에 제공되지 않으면 기본적으로 "peekLock" 모드로 설정됩니다. "peekLock" 모드에서 수신된 메시지를 정산 할 수도 있습니다.
이 수신기는 다음 3가지 방법 중 하나로 메시지를 수신하는 데 사용할 수 있습니다.
메시지 배열 가져오기
메시지 배열로 확인되는 promise를 반환하는 receiveMessages 함수를 사용합니다.
import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";
const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
const receiver = serviceBusClient.createReceiver("my-queue");
const myMessages = await receiver.receiveMessages(10);
메시지 처리기를 사용하여 구독Subscribe using a message handler
subscribe 메소드를 사용하여 메시지 핸들러를 설정하고 필요한 기간 동안 실행하도록 하십시오.
완료되면 전화를 걸어 receiver.close() 더 이상 메시지 수신을 중지하십시오.
import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";
const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
const receiver = serviceBusClient.createReceiver("my-queue");
const myMessageHandler = async (message) => {
// your code here
console.log(`message.body: ${message.body}`);
};
const myErrorHandler = async (args) => {
console.log(
`Error occurred with ${args.entityPath} within ${args.fullyQualifiedNamespace}: `,
args.error,
);
};
receiver.subscribe({
processMessage: myMessageHandler,
processError: myErrorHandler,
});
비동기 반복자 사용
getMessageIterator를 사용하여 메시지에 대한 비동기 반복자를 가져옵니다
import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";
const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
const receiver = serviceBusClient.createReceiver("my-queue");
for await (const message of receiver.getMessageIterator()) {
// your code here
}
메시지 정산
메시지를 받으면 메시지를 정산하려는 방법에 따라 , completeMessage()또는 abandonMessage()deferMessage() 수신자로 전화deadLetterMessage()할 수 있습니다.
자세한 내용은 수신된 메시지 해결을 참조하십시오.
배달 못한 편지 큐
배달 못한 편지 큐는 하위 큐입니다. 각 큐 또는 구독에는 고유한 배달 못한 편지 큐가 있습니다. 배달 못 한 편지 큐는 명시적으로 배달 못 한 편지(를 통해 receiver.deadLetterMessage())된 메시지 또는 최대 배달 횟수를 초과한 메시지를 저장합니다.
배달 못한 편지 하위 큐에 대한 수신자를 만드는 것은 구독 또는 큐에 대한 수신자를 만드는 것과 비슷합니다.
import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";
const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
// To receive from a queue's dead letter sub-queue
const deadLetterReceiverForQueue = serviceBusClient.createReceiver("queue", {
subQueueType: "deadLetter",
});
// To receive from a subscription's dead letter sub-queue
const deadLetterReceiverForSubscription = serviceBusClient.createReceiver("topic", "subscription", {
subQueueType: "deadLetter",
});
// Dead letter receivers work like any other receiver connected to a queue
// ex:
const messages = await deadLetterReceiverForQueue.receiveMessages(5);
for (const message of messages) {
console.log(`Dead lettered message: ${message.body}`);
}
데드 레터 큐를 더 철저하게 보여주는 전체 샘플:
세션을 사용하여 메시지 보내기
세션을 사용하려면 세션이 활성화된 Queue 또는 Subscription을 만들어야 합니다. 포털에서 이 기능을 구성하는 방법에 대한 자세한 내용은 여기에서 확인할 수 있습니다.
세션에 메시지를 보내려면 를 ServiceBusClient 사용하여 createSender를 사용하여 발신자를 만듭니다.
메시지를 보낼 때 메시지의 속성을 설정하여 sessionId 메시지가 올바른 세션에 도달하도록 합니다.
import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";
const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
const sender = serviceBusClient.createSender("my-session-queue");
await sender.sendMessages({
body: "my-message-body",
sessionId: "my-session",
});
세션 작동 방식에 대한 자세한 내용은 여기에서 확인할 수 있습니다.
세션에서 메시지 받기
세션을 사용하려면 세션이 활성화된 Queue 또는 Subscription을 만들어야 합니다. 포털에서 이 기능을 구성하는 방법에 대한 자세한 내용은 여기에서 확인할 수 있습니다.
세션을 사용할 수 없는 큐 또는 구독과 달리, 한 번에 하나의 수신기만 세션에서 읽을 수 있습니다. 이는 Service Bus에서 처리되는 세션을 잠그 면 적용됩니다. 개념적으로, 이것은 모드를 사용할 peekLock 때 메시지 잠금이 작동하는 방식과 유사합니다 - 메시지(또는 세션)가 잠겨 있을 때 수신자는 해당 메시지에 독점적으로 액세스할 수 있습니다.
세션을 열고 잠그려면 of ServiceBusClient 인스턴스를 사용하여 SessionReceiver를 만듭니다.
열려는 세션을 선택하는 방법에는 두 가지가 있습니다.
명명된 세션을 잠그는 를
sessionId지정합니다.const receiver = await serviceBusClient.acceptSession("my-session-queue", "my-session");세션 ID를 지정하지 마십시오. 이 경우 Service Bus는 아직 잠겨 있지 않은 사용 가능한 다음 세션을 찾습니다.
const receiver = await serviceBusClient.acceptNextSession("my-session-queue");의 속성을 통해
sessionId세션의 이름을 찾을 수 있습니다SessionReceiver. receiveMode가 옵션에 제공되지 않으면 기본적으로 "peekLock" 모드로 설정됩니다. "peekLock" 모드에서 수신된 메시지를 정산 할 수도 있습니다.
수신자가 생성되면 다음 3가지 메시지 수신 방법 중에서 선택할 수 있습니다.
세션 작동 방식에 대한 자세한 내용은 여기에서 확인할 수 있습니다.
메시지 세션 목록
큐나 구독에서 활성 메시지나 세션 상태가 있는 세션을 찾으려면 다음을 사용하세요 listMessageSessions():
import { DefaultAzureCredential } from "@azure/identity";
import { ServiceBusClient } from "@azure/service-bus";
const fullyQualifiedNamespace = "<name-of-service-bus-namespace>.servicebus.windows.net";
const credential = new DefaultAzureCredential();
const serviceBusClient = new ServiceBusClient(fullyQualifiedNamespace, credential);
// List all sessions with active messages or session state in a queue
for await (const sessionId of serviceBusClient.listMessageSessions("my-session-queue")) {
console.log("Session ID:", sessionId);
}
// List sessions in a subscription
for await (const sessionId of serviceBusClient.listMessageSessions("my-topic", "my-subscription")) {
console.log("Session ID:", sessionId);
}
// List only sessions whose stored session state was set or updated in the last seven days
const sessionStateUpdatedAfter = new Date(Date.now() - 7 * 24 * 60 * 60 * 1000);
for await (const sessionId of serviceBusClient.listMessageSessions("my-session-queue", {
sessionStateUpdatedAfter,
})) {
console.log("Recently updated session ID:", sessionId);
}
Service Bus 네임스페이스의 리소스 관리
ServiceBusAdministrationClient 엔터티(queues, topics 및 subscriptions) 및 구독 규칙에 대한 CRUD 작업으로 네임스페이스를 관리할 수 있습니다.
- Service Bus 연결 문자열과 유사한 의 AAD 자격 증명을
@azure/identityServiceBusClient사용한 인증을 지원합니다.
참고: Service Bus는 아직 네임스페이스에 대한 CORS 규칙 설정을 지원하지 않으므로 ServiceBusAdministrationClient 웹 보안을 사용하지 않도록 설정하지 않으면 브라우저에서 작동하지 않습니다. 자세한 내용은 여기를 참조하세요.
import { ServiceBusAdministrationClient } from "@azure/service-bus";
const queueName = "my-session-queue";
// Get the connection string from the portal
// OR
// use the token credential overload, provide the host name of your Service Bus instance and the AAD credentials from the @azure/identity library
const serviceBusAdministrationClient = new ServiceBusAdministrationClient("<connectionString>");
// Similarly, you can create topics and subscriptions as well.
const createQueueResponse = await serviceBusAdministrationClient.createQueue(queueName);
console.log("Created queue with name - ", createQueueResponse.name);
const queueRuntimeProperties =
await serviceBusAdministrationClient.getQueueRuntimeProperties(queueName);
console.log(`Number of messages in the queue = ${queueRuntimeProperties.totalMessageCount}`);
// Topic runtime properties additionally report the total number of SQL and correlation filters
// across all of the topic's subscriptions. These counts are served by the 2024-05 service API
// version and later; on an older version they are `undefined`.
const topicName = "my-topic";
const subscriptionName = "my-subscription";
await serviceBusAdministrationClient.createTopic(topicName);
// A new subscription carries a default rule with a SQL TrueFilter. Adding a correlation rule
// gives the topic one of each, so the counts below aggregate across the subscription's rules.
await serviceBusAdministrationClient.createSubscription(topicName, subscriptionName);
await serviceBusAdministrationClient.createRule(
topicName,
subscriptionName,
"my-correlation-rule",
{ correlationId: "my-correlation-id" },
);
const topicRuntimeProperties =
await serviceBusAdministrationClient.getTopicRuntimeProperties(topicName);
console.log(`SQL filter count = ${topicRuntimeProperties.sqlFilterCount}`);
console.log(`Correlation filter count = ${topicRuntimeProperties.correlationFilterCount}`);
await serviceBusAdministrationClient.deleteTopic(topicName);
await serviceBusAdministrationClient.deleteQueue(queueName);
- 참고용 샘플 - administrationClient.ts
Troubleshooting
문제 진단을 시작하기 위한 몇 가지 초기 단계는 다음과 같습니다. 자세한 내용은 Service Bus 문제 해결 가이드를 참조하세요.
AMQP 종속성
Service Bus 라이브러리는 AMQP 프로토콜을 통해 메시지를 보내고 받기 위해 연결을 관리하기 위해 rhea-promise 라이브러리에 의존합니다.
Logging
다음 환경 변수를 설정하여 이 라이브러리를 사용할 때 디버그 로그를 가져올 수 있습니다.
- Service Bus SDK에서 디버그 로그 가져오기
export DEBUG=azure*
- Service Bus SDK 및 프로토콜 수준 라이브러리에서 디버그 로그를 가져옵니다.
export DEBUG=azure*,rhea*
-
메시지 변환을 보는 데 관심이 없다면(콘솔/디스크 공간을 많이 차지함) 다음과 같이 환경 변수를 설정할
DEBUG수 있습니다.
export DEBUG=azure*,rhea*,-rhea:raw,-rhea:message,-azure:core-amqp:datatransformer
-
오류에만 관심이 있는 경우 다음과 같이 환경 변수를 설정할
DEBUG수 있습니다.
export DEBUG=azure:service-bus:error,azure:core-amqp:error,rhea-promise:error,rhea:events,rhea:frames,rhea:io,rhea:flow
파일에 로깅
-
DEBUG위와 같이 환경 변수를 설정합니다 - 다음과 같이 테스트 스크립트를 실행합니다.
- 테스트 스크립트의 로깅 문은
out.log이동하고 sdk의 로깅 문은debug.log이동합니다.node your-test-script.js > out.log 2>debug.log - 테스트 스크립트 및 sdk의 로깅 문은 stderr를 stdout(&1)로 리디렉션하여
out.log동일한 파일로 이동한 다음 stdout을 파일로 리디렉션합니다.node your-test-script.js >out.log 2>&1 - 테스트 스크립트 및 sdk의 로깅 문은
out.log동일한 파일로 이동합니다.node your-test-script.js &> out.log
다음 단계
이 라이브러리를 사용하여 Service Bus 큐, 항목 및 구독과 메시지를 주고받는 방법에 대한 자세한 예제는 샘플 디렉터리를 참조하세요.
Contributing
이 라이브러리에 기여하고 싶으시다면, 코드 빌드 및 테스트 방법에 대해 더 알고 싶다면 기여 가이드를 읽어보시기 바랍니다.
Azure SDK for JavaScript