[service-bus] Updating samples to fix a few issues: (#15430)
Updating samples to fix a few issues: - Show the right way to restart your receiver when using sessions (which don't do automatic retries like non-sessions). - Some of the samples printed almost too little console output to indicate what they were doing or didn't demonstrate the right techniques (asking for multiple messages at a time, etc..). Those have been updated as well. Fixes #14531
This commit is contained in:
Родитель
75e2780ee3
Коммит
2e56a4f08d
|
@ -29,14 +29,18 @@ export async function main() {
|
||||||
const queueReceiver = sbClient.createReceiver(queueName);
|
const queueReceiver = sbClient.createReceiver(queueName);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for (let i = 0; i < 20; i++) {
|
// peeking messages does not lock or remove messages from a queue or subscription.
|
||||||
const [message] = await queueReceiver.peekMessages(1);
|
// For locking and/or removal, look at the `receiveMessagesLoop` or `receiveMessagesStreaming` samples,
|
||||||
if (!message) {
|
// which cover using a receiver with a `receiveMode`.
|
||||||
console.log("No more messages to peek");
|
console.log(`Attempting to peek 10 messages at a time`);
|
||||||
break;
|
const peekedMessages = await queueReceiver.peekMessages(10);
|
||||||
}
|
|
||||||
console.log(`Peeking message #${i}: ${message.body}`);
|
console.log(`Got ${peekedMessages.length} messages.`);
|
||||||
|
|
||||||
|
for (let i = 0; i < peekedMessages.length; ++i) {
|
||||||
|
console.log(`Peeked message #${i}: ${peekedMessages[i].body}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
await queueReceiver.close();
|
await queueReceiver.close();
|
||||||
} finally {
|
} finally {
|
||||||
await sbClient.close();
|
await sbClient.close();
|
||||||
|
|
|
@ -31,9 +31,15 @@ export async function main() {
|
||||||
// To receive messages from sessions, use getSessionReceiver instead of getReceiver or look at
|
// To receive messages from sessions, use getSessionReceiver instead of getReceiver or look at
|
||||||
// the sample in sessions.ts file
|
// the sample in sessions.ts file
|
||||||
try {
|
try {
|
||||||
for (let i = 0; i < 10; i++) {
|
let allMessages = [];
|
||||||
const messages = await queueReceiver.receiveMessages(1, {
|
|
||||||
maxWaitTimeInMs: 5000
|
console.log(`Receiving 10 messages...`);
|
||||||
|
|
||||||
|
while (allMessages.length < 10) {
|
||||||
|
// NOTE: asking for 10 messages does not guarantee that we will return
|
||||||
|
// all 10 at once so we must loop until we get all the messages we expected.
|
||||||
|
const messages = await queueReceiver.receiveMessages(10, {
|
||||||
|
maxWaitTimeInMs: 60 * 1000
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!messages.length) {
|
if (!messages.length) {
|
||||||
|
@ -41,9 +47,17 @@ export async function main() {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Received message #${i}: ${messages[0].body}`);
|
console.log(`Received ${messages.length} messages`);
|
||||||
await queueReceiver.completeMessage(messages[0]);
|
allMessages.push(...messages);
|
||||||
|
|
||||||
|
for (let message of messages) {
|
||||||
|
console.log(` Message: '${message.body}'`);
|
||||||
|
|
||||||
|
// completing the message will remove it from the remote queue or subscription.
|
||||||
|
await queueReceiver.completeMessage(message);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
await queueReceiver.close();
|
await queueReceiver.close();
|
||||||
} finally {
|
} finally {
|
||||||
await sbClient.close();
|
await sbClient.close();
|
||||||
|
|
|
@ -14,7 +14,7 @@
|
||||||
* @azsdk-weight 100
|
* @azsdk-weight 100
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { ServiceBusClient, ServiceBusMessage } from "@azure/service-bus";
|
import { ServiceBusClient, ServiceBusMessage, ServiceBusMessageBatch } from "@azure/service-bus";
|
||||||
|
|
||||||
// Load the .env file if it exists
|
// Load the .env file if it exists
|
||||||
import * as dotenv from "dotenv";
|
import * as dotenv from "dotenv";
|
||||||
|
@ -24,12 +24,15 @@ dotenv.config();
|
||||||
const connectionString = process.env.SERVICEBUS_CONNECTION_STRING || "<connection string>";
|
const connectionString = process.env.SERVICEBUS_CONNECTION_STRING || "<connection string>";
|
||||||
const queueName = process.env.QUEUE_NAME || "<queue name>";
|
const queueName = process.env.QUEUE_NAME || "<queue name>";
|
||||||
|
|
||||||
const messages: ServiceBusMessage[] = [
|
const firstSetOfMessages: ServiceBusMessage[] = [
|
||||||
{ body: "Albert Einstein" },
|
{ body: "Albert Einstein" },
|
||||||
{ body: "Werner Heisenberg" },
|
{ body: "Werner Heisenberg" },
|
||||||
{ body: "Marie Curie" },
|
{ body: "Marie Curie" },
|
||||||
{ body: "Steven Hawking" },
|
{ body: "Steven Hawking" },
|
||||||
{ body: "Isaac Newton" },
|
{ body: "Isaac Newton" }
|
||||||
|
];
|
||||||
|
|
||||||
|
const secondSetOfMessages: ServiceBusMessage[] = [
|
||||||
{ body: "Niels Bohr" },
|
{ body: "Niels Bohr" },
|
||||||
{ body: "Michael Faraday" },
|
{ body: "Michael Faraday" },
|
||||||
{ body: "Galileo Galilei" },
|
{ body: "Galileo Galilei" },
|
||||||
|
@ -46,27 +49,29 @@ export async function main() {
|
||||||
try {
|
try {
|
||||||
// Tries to send all messages in a single batch.
|
// Tries to send all messages in a single batch.
|
||||||
// Will fail if the messages cannot fit in a batch.
|
// Will fail if the messages cannot fit in a batch.
|
||||||
await sender.sendMessages(messages);
|
console.log(`Sending the first 5 scientists (as an array)`);
|
||||||
|
await sender.sendMessages(firstSetOfMessages);
|
||||||
|
|
||||||
// Sends all messages using one or more ServiceBusMessageBatch objects as required
|
// Sends all messages using one or more ServiceBusMessageBatch objects as required
|
||||||
let batch = await sender.createMessageBatch();
|
let batch: ServiceBusMessageBatch = await sender.createMessageBatch();
|
||||||
|
|
||||||
for (let i = 0; i < messages.length; i++) {
|
for (const message of secondSetOfMessages) {
|
||||||
const message = messages[i];
|
|
||||||
if (!batch.tryAddMessage(message)) {
|
if (!batch.tryAddMessage(message)) {
|
||||||
// Send the current batch as it is full and create a new one
|
// Send the current batch as it is full and create a new one
|
||||||
await sender.sendMessages(batch);
|
await sender.sendMessages(batch);
|
||||||
batch = await sender.createMessageBatch();
|
batch = await sender.createMessageBatch();
|
||||||
|
|
||||||
if (!batch.tryAddMessage(messages[i])) {
|
if (!batch.tryAddMessage(message)) {
|
||||||
throw new Error("Message too big to fit in a batch");
|
throw new Error("Message too big to fit in a batch");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Send the batch
|
// Send the batch
|
||||||
|
console.log(`Sending the last 5 scientists (as a ServiceBusMessageBatch)`);
|
||||||
await sender.sendMessages(batch);
|
await sender.sendMessages(batch);
|
||||||
|
|
||||||
// Close the sender
|
// Close the sender
|
||||||
|
console.log(`Done sending, closing...`);
|
||||||
await sender.close();
|
await sender.close();
|
||||||
} finally {
|
} finally {
|
||||||
await sbClient.close();
|
await sbClient.close();
|
||||||
|
|
|
@ -43,12 +43,14 @@ export async function main() {
|
||||||
const sbClient = new ServiceBusClient(connectionString);
|
const sbClient = new ServiceBusClient(connectionString);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
console.log(`Sending 5 messages to 'session-1'`);
|
||||||
await sendMessage(sbClient, listOfScientists[0], "session-1");
|
await sendMessage(sbClient, listOfScientists[0], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[1], "session-1");
|
await sendMessage(sbClient, listOfScientists[1], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[2], "session-1");
|
await sendMessage(sbClient, listOfScientists[2], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[3], "session-1");
|
await sendMessage(sbClient, listOfScientists[3], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[4], "session-1");
|
await sendMessage(sbClient, listOfScientists[4], "session-1");
|
||||||
|
|
||||||
|
console.log(`Sending 5 messages to 'session-2'`);
|
||||||
await sendMessage(sbClient, listOfScientists[5], "session-2");
|
await sendMessage(sbClient, listOfScientists[5], "session-2");
|
||||||
await sendMessage(sbClient, listOfScientists[6], "session-2");
|
await sendMessage(sbClient, listOfScientists[6], "session-2");
|
||||||
await sendMessage(sbClient, listOfScientists[7], "session-2");
|
await sendMessage(sbClient, listOfScientists[7], "session-2");
|
||||||
|
@ -80,22 +82,46 @@ async function sendMessage(sbClient: ServiceBusClient, scientist: any, sessionId
|
||||||
|
|
||||||
async function receiveMessages(sbClient: ServiceBusClient, sessionId: string) {
|
async function receiveMessages(sbClient: ServiceBusClient, sessionId: string) {
|
||||||
// If receiving from a subscription you can use the acceptSession(topic, subscription, sessionId) overload
|
// If receiving from a subscription you can use the acceptSession(topic, subscription, sessionId) overload
|
||||||
|
let endDate: number | undefined;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
console.log(`Creating session receiver for session '${sessionId}'`);
|
||||||
const receiver = await sbClient.acceptSession(queueName, sessionId);
|
const receiver = await sbClient.acceptSession(queueName, sessionId);
|
||||||
|
|
||||||
|
const subscribePromise = new Promise((_, reject) => {
|
||||||
const processMessage = async (message: ServiceBusMessage) => {
|
const processMessage = async (message: ServiceBusMessage) => {
|
||||||
console.log(`Received: ${message.sessionId} - ${message.body} `);
|
console.log(`Received: ${message.sessionId} - ${message.body} `);
|
||||||
};
|
};
|
||||||
const processError = async (args: ProcessErrorArgs) => {
|
const processError = async (args: ProcessErrorArgs) => {
|
||||||
console.log(`>>>>> Error from error source ${args.errorSource} occurred: `, args.error);
|
console.log(`>>>>> Error from error source ${args.errorSource} occurred: `, args.error);
|
||||||
|
reject(args.error);
|
||||||
};
|
};
|
||||||
|
|
||||||
receiver.subscribe({
|
receiver.subscribe({
|
||||||
processMessage,
|
processMessage,
|
||||||
processError
|
processError
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
await delay(5000);
|
const now = Date.now();
|
||||||
|
endDate = endDate ?? now + 20000;
|
||||||
|
let remainingTime: number = endDate - now;
|
||||||
|
|
||||||
|
console.log(`Waiting for ${remainingTime} milliseconds for messages to arrive.`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await Promise.race([subscribePromise, delay(remainingTime)]);
|
||||||
|
|
||||||
|
// wait time has expired, we can stop listening.
|
||||||
|
console.log(`Time has expired, closing receiver for session '${sessionId}'`);
|
||||||
|
|
||||||
await receiver.close();
|
await receiver.close();
|
||||||
|
break;
|
||||||
|
} catch (err) {
|
||||||
|
// `err` was already logged part of `processError` above.
|
||||||
|
await receiver.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch((err) => {
|
main().catch((err) => {
|
||||||
|
|
|
@ -28,14 +28,18 @@ async function main() {
|
||||||
const queueReceiver = sbClient.createReceiver(queueName);
|
const queueReceiver = sbClient.createReceiver(queueName);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for (let i = 0; i < 20; i++) {
|
// peeking messages does not lock or remove messages from a queue or subscription.
|
||||||
const [message] = await queueReceiver.peekMessages(1);
|
// For locking and/or removal, look at the `receiveMessagesLoop` or `receiveMessagesStreaming` samples,
|
||||||
if (!message) {
|
// which cover using a receiver with a `receiveMode`.
|
||||||
console.log("No more messages to peek");
|
console.log(`Attempting to peek 10 messages at a time`);
|
||||||
break;
|
const peekedMessages = await queueReceiver.peekMessages(10);
|
||||||
}
|
|
||||||
console.log(`Peeking message #${i}: ${message.body}`);
|
console.log(`Got ${peekedMessages.length} messages.`);
|
||||||
|
|
||||||
|
for (let i = 0; i < peekedMessages.length; ++i) {
|
||||||
|
console.log(`Peeked message #${i}: ${peekedMessages[i].body}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
await queueReceiver.close();
|
await queueReceiver.close();
|
||||||
} finally {
|
} finally {
|
||||||
await sbClient.close();
|
await sbClient.close();
|
||||||
|
|
|
@ -30,9 +30,15 @@ async function main() {
|
||||||
// To receive messages from sessions, use getSessionReceiver instead of getReceiver or look at
|
// To receive messages from sessions, use getSessionReceiver instead of getReceiver or look at
|
||||||
// the sample in sessions.ts file
|
// the sample in sessions.ts file
|
||||||
try {
|
try {
|
||||||
for (let i = 0; i < 10; i++) {
|
let allMessages = [];
|
||||||
const messages = await queueReceiver.receiveMessages(1, {
|
|
||||||
maxWaitTimeInMs: 5000
|
console.log(`Receiving 10 messages...`);
|
||||||
|
|
||||||
|
while (allMessages.length < 10) {
|
||||||
|
// NOTE: asking for 10 messages does not guarantee that we will return
|
||||||
|
// all 10 at once so we must loop until we get all the messages we expected.
|
||||||
|
const messages = await queueReceiver.receiveMessages(10, {
|
||||||
|
maxWaitTimeInMs: 60 * 1000
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!messages.length) {
|
if (!messages.length) {
|
||||||
|
@ -40,9 +46,17 @@ async function main() {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Received message #${i}: ${messages[0].body}`);
|
console.log(`Received ${messages.length} messages`);
|
||||||
await queueReceiver.completeMessage(messages[0]);
|
allMessages.push(...messages);
|
||||||
|
|
||||||
|
for (let message of messages) {
|
||||||
|
console.log(` Message: '${message.body}'`);
|
||||||
|
|
||||||
|
// completing the message will remove it from the remote queue or subscription.
|
||||||
|
await queueReceiver.completeMessage(message);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
await queueReceiver.close();
|
await queueReceiver.close();
|
||||||
} finally {
|
} finally {
|
||||||
await sbClient.close();
|
await sbClient.close();
|
||||||
|
|
|
@ -23,12 +23,15 @@ dotenv.config();
|
||||||
const connectionString = process.env.SERVICEBUS_CONNECTION_STRING || "<connection string>";
|
const connectionString = process.env.SERVICEBUS_CONNECTION_STRING || "<connection string>";
|
||||||
const queueName = process.env.QUEUE_NAME || "<queue name>";
|
const queueName = process.env.QUEUE_NAME || "<queue name>";
|
||||||
|
|
||||||
const messages = [
|
const firstSetOfMessages = [
|
||||||
{ body: "Albert Einstein" },
|
{ body: "Albert Einstein" },
|
||||||
{ body: "Werner Heisenberg" },
|
{ body: "Werner Heisenberg" },
|
||||||
{ body: "Marie Curie" },
|
{ body: "Marie Curie" },
|
||||||
{ body: "Steven Hawking" },
|
{ body: "Steven Hawking" },
|
||||||
{ body: "Isaac Newton" },
|
{ body: "Isaac Newton" }
|
||||||
|
];
|
||||||
|
|
||||||
|
const secondSetOfMessages = [
|
||||||
{ body: "Niels Bohr" },
|
{ body: "Niels Bohr" },
|
||||||
{ body: "Michael Faraday" },
|
{ body: "Michael Faraday" },
|
||||||
{ body: "Galileo Galilei" },
|
{ body: "Galileo Galilei" },
|
||||||
|
@ -45,27 +48,29 @@ async function main() {
|
||||||
try {
|
try {
|
||||||
// Tries to send all messages in a single batch.
|
// Tries to send all messages in a single batch.
|
||||||
// Will fail if the messages cannot fit in a batch.
|
// Will fail if the messages cannot fit in a batch.
|
||||||
await sender.sendMessages(messages);
|
console.log(`Sending the first 5 scientists (as an array)`);
|
||||||
|
await sender.sendMessages(firstSetOfMessages);
|
||||||
|
|
||||||
// Sends all messages using one or more ServiceBusMessageBatch objects as required
|
// Sends all messages using one or more ServiceBusMessageBatch objects as required
|
||||||
let batch = await sender.createMessageBatch();
|
let batch = await sender.createMessageBatch();
|
||||||
|
|
||||||
for (let i = 0; i < messages.length; i++) {
|
for (const message of secondSetOfMessages) {
|
||||||
const message = messages[i];
|
|
||||||
if (!batch.tryAddMessage(message)) {
|
if (!batch.tryAddMessage(message)) {
|
||||||
// Send the current batch as it is full and create a new one
|
// Send the current batch as it is full and create a new one
|
||||||
await sender.sendMessages(batch);
|
await sender.sendMessages(batch);
|
||||||
batch = await sender.createMessageBatch();
|
batch = await sender.createMessageBatch();
|
||||||
|
|
||||||
if (!batch.tryAddMessage(messages[i])) {
|
if (!batch.tryAddMessage(message)) {
|
||||||
throw new Error("Message too big to fit in a batch");
|
throw new Error("Message too big to fit in a batch");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Send the batch
|
// Send the batch
|
||||||
|
console.log(`Sending the last 5 scientists (as a ServiceBusMessageBatch)`);
|
||||||
await sender.sendMessages(batch);
|
await sender.sendMessages(batch);
|
||||||
|
|
||||||
// Close the sender
|
// Close the sender
|
||||||
|
console.log(`Done sending, closing...`);
|
||||||
await sender.close();
|
await sender.close();
|
||||||
} finally {
|
} finally {
|
||||||
await sbClient.close();
|
await sbClient.close();
|
||||||
|
|
|
@ -42,12 +42,14 @@ async function main() {
|
||||||
const sbClient = new ServiceBusClient(connectionString);
|
const sbClient = new ServiceBusClient(connectionString);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
console.log(`Sending 5 messages to 'session-1'`);
|
||||||
await sendMessage(sbClient, listOfScientists[0], "session-1");
|
await sendMessage(sbClient, listOfScientists[0], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[1], "session-1");
|
await sendMessage(sbClient, listOfScientists[1], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[2], "session-1");
|
await sendMessage(sbClient, listOfScientists[2], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[3], "session-1");
|
await sendMessage(sbClient, listOfScientists[3], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[4], "session-1");
|
await sendMessage(sbClient, listOfScientists[4], "session-1");
|
||||||
|
|
||||||
|
console.log(`Sending 5 messages to 'session-2'`);
|
||||||
await sendMessage(sbClient, listOfScientists[5], "session-2");
|
await sendMessage(sbClient, listOfScientists[5], "session-2");
|
||||||
await sendMessage(sbClient, listOfScientists[6], "session-2");
|
await sendMessage(sbClient, listOfScientists[6], "session-2");
|
||||||
await sendMessage(sbClient, listOfScientists[7], "session-2");
|
await sendMessage(sbClient, listOfScientists[7], "session-2");
|
||||||
|
@ -79,22 +81,46 @@ async function sendMessage(sbClient, scientist, sessionId) {
|
||||||
|
|
||||||
async function receiveMessages(sbClient, sessionId) {
|
async function receiveMessages(sbClient, sessionId) {
|
||||||
// If receiving from a subscription you can use the acceptSession(topic, subscription, sessionId) overload
|
// If receiving from a subscription you can use the acceptSession(topic, subscription, sessionId) overload
|
||||||
|
let endDate;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
console.log(`Creating session receiver for session '${sessionId}'`);
|
||||||
const receiver = await sbClient.acceptSession(queueName, sessionId);
|
const receiver = await sbClient.acceptSession(queueName, sessionId);
|
||||||
|
|
||||||
|
const subscribePromise = new Promise((_, reject) => {
|
||||||
const processMessage = async (message) => {
|
const processMessage = async (message) => {
|
||||||
console.log(`Received: ${message.sessionId} - ${message.body} `);
|
console.log(`Received: ${message.sessionId} - ${message.body} `);
|
||||||
};
|
};
|
||||||
const processError = async (args) => {
|
const processError = async (args) => {
|
||||||
console.log(`>>>>> Error from error source ${args.errorSource} occurred: `, args.error);
|
console.log(`>>>>> Error from error source ${args.errorSource} occurred: `, args.error);
|
||||||
|
reject(args.error);
|
||||||
};
|
};
|
||||||
|
|
||||||
receiver.subscribe({
|
receiver.subscribe({
|
||||||
processMessage,
|
processMessage,
|
||||||
processError
|
processError
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
await delay(5000);
|
const now = Date.now();
|
||||||
|
endDate = endDate ?? now + 20000;
|
||||||
|
let remainingTime = endDate - now;
|
||||||
|
|
||||||
|
console.log(`Waiting for ${remainingTime} milliseconds for messages to arrive.`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await Promise.race([subscribePromise, delay(remainingTime)]);
|
||||||
|
|
||||||
|
// wait time has expired, we can stop listening.
|
||||||
|
console.log(`Time has expired, closing receiver for session '${sessionId}'`);
|
||||||
|
|
||||||
await receiver.close();
|
await receiver.close();
|
||||||
|
break;
|
||||||
|
} catch (err) {
|
||||||
|
// `err` was already logged part of `processError` above.
|
||||||
|
await receiver.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch((err) => {
|
main().catch((err) => {
|
||||||
|
|
|
@ -28,14 +28,18 @@ export async function main() {
|
||||||
const queueReceiver = sbClient.createReceiver(queueName);
|
const queueReceiver = sbClient.createReceiver(queueName);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
for (let i = 0; i < 20; i++) {
|
// peeking messages does not lock or remove messages from a queue or subscription.
|
||||||
const [message] = await queueReceiver.peekMessages(1);
|
// For locking and/or removal, look at the `receiveMessagesLoop` or `receiveMessagesStreaming` samples,
|
||||||
if (!message) {
|
// which cover using a receiver with a `receiveMode`.
|
||||||
console.log("No more messages to peek");
|
console.log(`Attempting to peek 10 messages at a time`);
|
||||||
break;
|
const peekedMessages = await queueReceiver.peekMessages(10);
|
||||||
}
|
|
||||||
console.log(`Peeking message #${i}: ${message.body}`);
|
console.log(`Got ${peekedMessages.length} messages.`);
|
||||||
|
|
||||||
|
for (let i = 0; i < peekedMessages.length; ++i) {
|
||||||
|
console.log(`Peeked message #${i}: ${peekedMessages[i].body}`);
|
||||||
}
|
}
|
||||||
|
|
||||||
await queueReceiver.close();
|
await queueReceiver.close();
|
||||||
} finally {
|
} finally {
|
||||||
await sbClient.close();
|
await sbClient.close();
|
||||||
|
|
|
@ -30,9 +30,15 @@ export async function main() {
|
||||||
// To receive messages from sessions, use getSessionReceiver instead of getReceiver or look at
|
// To receive messages from sessions, use getSessionReceiver instead of getReceiver or look at
|
||||||
// the sample in sessions.ts file
|
// the sample in sessions.ts file
|
||||||
try {
|
try {
|
||||||
for (let i = 0; i < 10; i++) {
|
let allMessages = [];
|
||||||
const messages = await queueReceiver.receiveMessages(1, {
|
|
||||||
maxWaitTimeInMs: 5000
|
console.log(`Receiving 10 messages...`);
|
||||||
|
|
||||||
|
while (allMessages.length < 10) {
|
||||||
|
// NOTE: asking for 10 messages does not guarantee that we will return
|
||||||
|
// all 10 at once so we must loop until we get all the messages we expected.
|
||||||
|
const messages = await queueReceiver.receiveMessages(10, {
|
||||||
|
maxWaitTimeInMs: 60 * 1000
|
||||||
});
|
});
|
||||||
|
|
||||||
if (!messages.length) {
|
if (!messages.length) {
|
||||||
|
@ -40,9 +46,17 @@ export async function main() {
|
||||||
break;
|
break;
|
||||||
}
|
}
|
||||||
|
|
||||||
console.log(`Received message #${i}: ${messages[0].body}`);
|
console.log(`Received ${messages.length} messages`);
|
||||||
await queueReceiver.completeMessage(messages[0]);
|
allMessages.push(...messages);
|
||||||
|
|
||||||
|
for (let message of messages) {
|
||||||
|
console.log(` Message: '${message.body}'`);
|
||||||
|
|
||||||
|
// completing the message will remove it from the remote queue or subscription.
|
||||||
|
await queueReceiver.completeMessage(message);
|
||||||
}
|
}
|
||||||
|
}
|
||||||
|
|
||||||
await queueReceiver.close();
|
await queueReceiver.close();
|
||||||
} finally {
|
} finally {
|
||||||
await sbClient.close();
|
await sbClient.close();
|
||||||
|
|
|
@ -13,7 +13,7 @@
|
||||||
* @summary Demonstrates how to send messages to Service Bus Queue/Topic
|
* @summary Demonstrates how to send messages to Service Bus Queue/Topic
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { ServiceBusClient, ServiceBusMessage } from "@azure/service-bus";
|
import { ServiceBusClient, ServiceBusMessage, ServiceBusMessageBatch } from "@azure/service-bus";
|
||||||
|
|
||||||
// Load the .env file if it exists
|
// Load the .env file if it exists
|
||||||
import * as dotenv from "dotenv";
|
import * as dotenv from "dotenv";
|
||||||
|
@ -23,12 +23,15 @@ dotenv.config();
|
||||||
const connectionString = process.env.SERVICEBUS_CONNECTION_STRING || "<connection string>";
|
const connectionString = process.env.SERVICEBUS_CONNECTION_STRING || "<connection string>";
|
||||||
const queueName = process.env.QUEUE_NAME || "<queue name>";
|
const queueName = process.env.QUEUE_NAME || "<queue name>";
|
||||||
|
|
||||||
const messages: ServiceBusMessage[] = [
|
const firstSetOfMessages: ServiceBusMessage[] = [
|
||||||
{ body: "Albert Einstein" },
|
{ body: "Albert Einstein" },
|
||||||
{ body: "Werner Heisenberg" },
|
{ body: "Werner Heisenberg" },
|
||||||
{ body: "Marie Curie" },
|
{ body: "Marie Curie" },
|
||||||
{ body: "Steven Hawking" },
|
{ body: "Steven Hawking" },
|
||||||
{ body: "Isaac Newton" },
|
{ body: "Isaac Newton" }
|
||||||
|
];
|
||||||
|
|
||||||
|
const secondSetOfMessages: ServiceBusMessage[] = [
|
||||||
{ body: "Niels Bohr" },
|
{ body: "Niels Bohr" },
|
||||||
{ body: "Michael Faraday" },
|
{ body: "Michael Faraday" },
|
||||||
{ body: "Galileo Galilei" },
|
{ body: "Galileo Galilei" },
|
||||||
|
@ -45,27 +48,29 @@ export async function main() {
|
||||||
try {
|
try {
|
||||||
// Tries to send all messages in a single batch.
|
// Tries to send all messages in a single batch.
|
||||||
// Will fail if the messages cannot fit in a batch.
|
// Will fail if the messages cannot fit in a batch.
|
||||||
await sender.sendMessages(messages);
|
console.log(`Sending the first 5 scientists (as an array)`);
|
||||||
|
await sender.sendMessages(firstSetOfMessages);
|
||||||
|
|
||||||
// Sends all messages using one or more ServiceBusMessageBatch objects as required
|
// Sends all messages using one or more ServiceBusMessageBatch objects as required
|
||||||
let batch = await sender.createMessageBatch();
|
let batch: ServiceBusMessageBatch = await sender.createMessageBatch();
|
||||||
|
|
||||||
for (let i = 0; i < messages.length; i++) {
|
for (const message of secondSetOfMessages) {
|
||||||
const message = messages[i];
|
|
||||||
if (!batch.tryAddMessage(message)) {
|
if (!batch.tryAddMessage(message)) {
|
||||||
// Send the current batch as it is full and create a new one
|
// Send the current batch as it is full and create a new one
|
||||||
await sender.sendMessages(batch);
|
await sender.sendMessages(batch);
|
||||||
batch = await sender.createMessageBatch();
|
batch = await sender.createMessageBatch();
|
||||||
|
|
||||||
if (!batch.tryAddMessage(messages[i])) {
|
if (!batch.tryAddMessage(message)) {
|
||||||
throw new Error("Message too big to fit in a batch");
|
throw new Error("Message too big to fit in a batch");
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
// Send the batch
|
// Send the batch
|
||||||
|
console.log(`Sending the last 5 scientists (as a ServiceBusMessageBatch)`);
|
||||||
await sender.sendMessages(batch);
|
await sender.sendMessages(batch);
|
||||||
|
|
||||||
// Close the sender
|
// Close the sender
|
||||||
|
console.log(`Done sending, closing...`);
|
||||||
await sender.close();
|
await sender.close();
|
||||||
} finally {
|
} finally {
|
||||||
await sbClient.close();
|
await sbClient.close();
|
||||||
|
|
|
@ -42,12 +42,14 @@ export async function main() {
|
||||||
const sbClient = new ServiceBusClient(connectionString);
|
const sbClient = new ServiceBusClient(connectionString);
|
||||||
|
|
||||||
try {
|
try {
|
||||||
|
console.log(`Sending 5 messages to 'session-1'`);
|
||||||
await sendMessage(sbClient, listOfScientists[0], "session-1");
|
await sendMessage(sbClient, listOfScientists[0], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[1], "session-1");
|
await sendMessage(sbClient, listOfScientists[1], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[2], "session-1");
|
await sendMessage(sbClient, listOfScientists[2], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[3], "session-1");
|
await sendMessage(sbClient, listOfScientists[3], "session-1");
|
||||||
await sendMessage(sbClient, listOfScientists[4], "session-1");
|
await sendMessage(sbClient, listOfScientists[4], "session-1");
|
||||||
|
|
||||||
|
console.log(`Sending 5 messages to 'session-2'`);
|
||||||
await sendMessage(sbClient, listOfScientists[5], "session-2");
|
await sendMessage(sbClient, listOfScientists[5], "session-2");
|
||||||
await sendMessage(sbClient, listOfScientists[6], "session-2");
|
await sendMessage(sbClient, listOfScientists[6], "session-2");
|
||||||
await sendMessage(sbClient, listOfScientists[7], "session-2");
|
await sendMessage(sbClient, listOfScientists[7], "session-2");
|
||||||
|
@ -79,22 +81,46 @@ async function sendMessage(sbClient: ServiceBusClient, scientist: any, sessionId
|
||||||
|
|
||||||
async function receiveMessages(sbClient: ServiceBusClient, sessionId: string) {
|
async function receiveMessages(sbClient: ServiceBusClient, sessionId: string) {
|
||||||
// If receiving from a subscription you can use the acceptSession(topic, subscription, sessionId) overload
|
// If receiving from a subscription you can use the acceptSession(topic, subscription, sessionId) overload
|
||||||
|
let endDate: number | undefined;
|
||||||
|
|
||||||
|
while (true) {
|
||||||
|
console.log(`Creating session receiver for session '${sessionId}'`);
|
||||||
const receiver = await sbClient.acceptSession(queueName, sessionId);
|
const receiver = await sbClient.acceptSession(queueName, sessionId);
|
||||||
|
|
||||||
|
const subscribePromise = new Promise((_, reject) => {
|
||||||
const processMessage = async (message: ServiceBusMessage) => {
|
const processMessage = async (message: ServiceBusMessage) => {
|
||||||
console.log(`Received: ${message.sessionId} - ${message.body} `);
|
console.log(`Received: ${message.sessionId} - ${message.body} `);
|
||||||
};
|
};
|
||||||
const processError = async (args: ProcessErrorArgs) => {
|
const processError = async (args: ProcessErrorArgs) => {
|
||||||
console.log(`>>>>> Error from error source ${args.errorSource} occurred: `, args.error);
|
console.log(`>>>>> Error from error source ${args.errorSource} occurred: `, args.error);
|
||||||
|
reject(args.error);
|
||||||
};
|
};
|
||||||
|
|
||||||
receiver.subscribe({
|
receiver.subscribe({
|
||||||
processMessage,
|
processMessage,
|
||||||
processError
|
processError
|
||||||
});
|
});
|
||||||
|
});
|
||||||
|
|
||||||
await delay(5000);
|
const now = Date.now();
|
||||||
|
endDate = endDate ?? now + 20000;
|
||||||
|
let remainingTime: number = endDate - now;
|
||||||
|
|
||||||
|
console.log(`Waiting for ${remainingTime} milliseconds for messages to arrive.`);
|
||||||
|
|
||||||
|
try {
|
||||||
|
await Promise.race([subscribePromise, delay(remainingTime)]);
|
||||||
|
|
||||||
|
// wait time has expired, we can stop listening.
|
||||||
|
console.log(`Time has expired, closing receiver for session '${sessionId}'`);
|
||||||
|
|
||||||
await receiver.close();
|
await receiver.close();
|
||||||
|
break;
|
||||||
|
} catch (err) {
|
||||||
|
// `err` was already logged part of `processError` above.
|
||||||
|
await receiver.close();
|
||||||
|
}
|
||||||
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
main().catch((err) => {
|
main().catch((err) => {
|
||||||
|
|
Загрузка…
Ссылка в новой задаче