Azure Service Bus is a highly-reliable cloud messaging service from Microsoft.
Use the client library @azure/service-bus
in your application to
Resources for the v7.0.0-preview.6 of @azure/service-bus
:
Source code | Package (npm) | API Reference Documentation | Product documentation | Samples
NOTE: This document has instructions, links and code snippets for the preview of the next version of the
@azure/service-bus
package which has different APIs than the stable version. To use the stable version of the library use the below resources.
Source code or Readme for v1.1.9 | Package for v1.1.9 (npm) | API Reference Documentation for v1.1.9 | Samples for @azure/service-bus v1.1.x
We also provide a migration guide for users familiar with the stable package that would like to try the preview: migration guide to move from Service Bus V1 to Service Bus V7 Preview
Install the preview version for the Azure Service Bus client library using npm
npm install @azure/service-bus@next
You must have an Azure subscription and a Service Bus Namespace to use this package. If you are using this package in a Node.js application, then use Node.js 8.x or higher.
TypeScript users need to have Node type definitions installed:
npm install @types/node
You also need to enable compilerOptions.allowSyntheticDefaultImports
in your tsconfig.json. Note that if you have enabled compilerOptions.esModuleInterop
, allowSyntheticDefaultImports
is enabled by default. See TypeScript's compiler options handbook for more information.
To use this client library in the browser, first you need to use a bundler. For details on how to do this, please refer to our bundling documentation.
Interaction with Service Bus starts with an instance of the ServiceBusClient class.
You can instantiate this class using its constructors:
name-of-service-bus-instance.servicebus.windows.net
.
If you're using an own implementation of the TokenCredential
interface against AAD, then set the "scopes" for service-bus to be ["https://servicebus.azure.net//user_impersonation"]
to get the appropriate token.Once you've initialized a ServiceBusClient
, you can interact with these resources within a
Service Bus Namespace:
For more information about these resources, see What is Azure Service Bus?.
To interact with these resources, one should be familiar with the following SDK concepts:
Sender
created using ServiceBusClient.createSender()
.Receiver
created using ServiceBusClient.createReceiver()
.SessionReceiver
created using ServiceBusClient.createSessionReceiver()
.Please note that the Queues, Topics and Subscriptions should be created prior to using this library.
The following sections provide code snippets that cover some of the common tasks using Azure Service Bus
Once you have created an instance of a ServiceBusClient
class, you can get a Sender
using the createSender method.
This gives you a sender which you can use to send messages.
const sender = serviceBusClient.createSender("my-queue");
// sending a single message
await sender.sendMessages({
body: "my-message-body"
});
// sending multiple messages
await sender.sendMessages([
{
body: "my-message-body"
},
{
body: "another-message-body"
}
]);
Once you have created an instance of a ServiceBusClient
class, you can get a Receiver
using the createReceiver method.
const receiver = serviceBusClient.createReceiver("my-queue");
There are two receiveMode
s available.
If the receiveMode is not provided in the options, it defaults to the "peekLock" mode. You can also settle the messages received in "peekLock" mode.
You can use this receiver in one of 3 ways to receive messages:
Use the receiveMessages function which returns a promise that resolves to an array of messages.
const myMessages = await receiver.receiveMessages(10);
Use the subscribe method to set up message handlers and have it running as long as you need.
When you are done, call receiver.close()
to stop receiving any more messages.
const myMessageHandler = async (message) => {
// your code here
};
const myErrorHandler = async (error) => {
console.log(error);
};
receiver.subscribe({
processMessage: myMessageHandler,
processError: myErrorHandler
});
Use the getMessageIterator to get an async iterator over messages
for await (let message of receiver.getMessageIterator()) {
// your code here
}
Once you receive a message you can call complete()
, abandon()
, defer()
or deadletter()
on it
based on how you want to settle the message.
To learn more, please read Settling Received Messages
Using sessions requires you to create a session enabled Queue or Subscription. You can read more about how to configure this feature in the portal here.
In order to send messages to a session, use the ServiceBusClient
to create a sender using
createSender. This gives you a sender which you can use to send messages.
When sending the message, set the sessionId
property in the message to ensure
your message lands in the right session.
const sender = serviceBusClient.createSender("my-session-queue");
await sender.sendMessages({
body: "my-message-body",
sessionId: "my-session"
});
You can read more about how sessions work here.
Using sessions requires you to create a session enabled Queue or Subscription. You can read more about how to configure this feature in the portal here.
Unlike non-session-enabled Queues or Subscriptions, only a single receiver
can read from a session at any time. This is enforced by locking a session,
which is handled by Service Bus. Conceptually, this is similar to how message
locking works when using peekLock
mode - when a message (or session) is
locked your receiver has exclusive access to it.
In order to open and lock a session, use an instance of ServiceBusClient
to create a SessionReceiver using createSessionReceiver.
There are two ways of choosing which session to open:
Specify a sessionId
, which locks a named session.
const receiver = await serviceBusClient.createSessionReceiver("my-session-queue", {
sessionId: "my-session"
});
Do not specify a session id. In this case Service Bus will find the next available session that is not already locked.
const receiver = await serviceBusClient.createSessionReceiver("my-session-queue");
You can find the name of the session via the sessionId
property on the SessionReceiver
.
If the receiveMode is not provided in the options, it defaults to the "peekLock" mode.
You can also settle the messages received in "peekLock" mode.
Once the receiver is created you can use choose between 3 ways to receive messages:
You can read more about how sessions work here.
ServiceBusAdministrationClient
lets you manage a namespace with CRUD operations on the entities(queues, topics, and subscriptions) and on the rules of a subscription.
@azure/identity
similar to the ServiceBusClient
.// 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);
await serviceBusAdministrationClient.deleteQueue(queueName);
The Service Bus library depends on the rhea-promise library for managing connections, sending and receiving messages over the AMQP protocol.
You can set the following environment variable to get the debug logs when using this library.
export DEBUG=azure*
export DEBUG=azure*,rhea*
DEBUG
environment variable as follows:export DEBUG=azure*,rhea*,-rhea:raw,-rhea:message,-azure:core-amqp:datatransformer
DEBUG
environment variable as follows:export DEBUG=azure:service-bus:error,azure-core-amqp:error,rhea-promise:error,rhea:events,rhea:frames,rhea:io,rhea:flow
DEBUG
environment variable as shown aboveout.log
and logging statements from the sdk go to debug.log
.node your-test-script.js > out.log 2>debug.log
out.log
by redirecting stderr to stdout (&1), and then redirect stdout to a file:node your-test-script.js >out.log 2>&1
out.log
. node your-test-script.js &> out.log
Please take a look at the samples directory for detailed examples on how to use this library to send and receive messages to/from Service Bus Queues, Topics and Subscriptions.
If you'd like to contribute to this library, please read the contributing guide to learn more about how to build and test the code.
Generated using TypeDoc