Envíe mensajes a un tema de Azure Service Bus y reciba mensajes de las suscripciones a ese tema (JavaScript)

En este tutorial aprenderá a usar el paquete @azure/service-bus de un programa de JavaScript para enviar mensajes a un tema de Service Bus y recibirlos de una suscripción de Service Bus a ese tema.

Requisitos previos

Nota

Uso del Administrador de paquetes para Node (NPM) para instalar el paquete

Para instalar el paquete de npm para Service Bus, abra un símbolo del sistema que tenga npm en la ruta de acceso, cambie el directorio a la carpeta en la que quiere colocar los ejemplos y ejecute este comando.

npm install @azure/service-bus

Envío de mensajes a un tema

En el código de ejemplo siguiente se muestra cómo enviar un lote de mensajes a un tema de Service Bus. Vea los comentarios de código para obtener más detalles.

  1. Abra el editor que prefiera, como Visual Studio Code

  2. Cree un archivo denominado sendtotopic.js y pegue en él el código siguiente. Este código enviará un mensaje al tema.

    const { ServiceBusClient } = require("@azure/service-bus");
    
    const connectionString = "<SERVICE BUS NAMESPACE CONNECTION STRING>"
    const topicName = "<TOPIC NAME>";
    
    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" }
     ];
    
     async function main() {
        // create a Service Bus client using the connection string to the Service Bus namespace
        const sbClient = new ServiceBusClient(connectionString);
    
        // createSender() can also be used to create a sender for a queue.
        const sender = sbClient.createSender(topicName);
    
        try {
            // Tries to send all messages in a single batch.
            // Will fail if the messages cannot fit in a batch.
            // await sender.sendMessages(messages);
    
            // create a batch object
            let batch = await sender.createMessageBatch(); 
            for (let i = 0; i < messages.length; i++) {
                // for each message in the arry         
    
                // try to add the message to the batch
                if (!batch.tryAddMessage(messages[i])) {            
                    // if it fails to add the message to the current batch
                    // send the current batch as it is full
                    await sender.sendMessages(batch);
    
                    // then, create a new batch 
                    batch = await sender.createMessageBatch();
    
                    // now, add the message failed to be added to the previous batch to this batch
                    if (!batch.tryAddMessage(messages[i])) {
                        // if it still can't be added to the batch, the message is probably too big to fit in a batch
                        throw new Error("Message too big to fit in a batch");
                    }
                }
            }
    
            // Send the last created batch of messages to the topic
            await sender.sendMessages(batch);
    
            console.log(`Sent a batch of messages to the topic: ${topicName}`);
    
            // Close the sender
            await sender.close();
        } finally {
            await sbClient.close();
        }
    }
    
    // call the main function
    main().catch((err) => {
        console.log("Error occurred: ", err);
        process.exit(1);
     });    
    
  3. Reemplace <SERVICE BUS NAMESPACE CONNECTION STRING> por la cadena de conexión del espacio de nombres de Service Bus.

  4. Reemplace <TOPIC NAME> por el nombre del tema.

  5. Después, ejecute el comando en un símbolo del sistema para ejecutar este archivo.

    node sendtotopic.js 
    
  6. Debería ver la siguiente salida.

    Sent a batch of messages to the topic: mytopic
    

Recepción de mensajes de una suscripción

  1. Abra el editor que prefiera, como Visual Studio Code

  2. Cree un archivo denominado receivefromsubscription.js y pegue en él el código siguiente. Vea los comentarios de código para obtener más detalles.

    const { delay, ServiceBusClient, ServiceBusMessage } = require("@azure/service-bus");
    
    const connectionString = "<SERVICE BUS NAMESPACE CONNECTION STRING>"
    const topicName = "<TOPIC NAME>";
    const subscriptionName = "<SUBSCRIPTION NAME>";
    
     async function main() {
        // create a Service Bus client using the connection string to the Service Bus namespace
        const sbClient = new ServiceBusClient(connectionString);
    
        // createReceiver() can also be used to create a receiver for a queue.
        const receiver = sbClient.createReceiver(topicName, subscriptionName);
    
        // function to handle messages
        const myMessageHandler = async (messageReceived) => {
            console.log(`Received message: ${messageReceived.body}`);
        };
    
        // function to handle any errors
        const myErrorHandler = async (error) => {
            console.log(error);
        };
    
        // subscribe and specify the message and error handlers
        receiver.subscribe({
            processMessage: myMessageHandler,
            processError: myErrorHandler
        });
    
        // Waiting long enough before closing the sender to send messages
        await delay(5000);
    
        await receiver.close(); 
        await sbClient.close();
    }
    
    // call the main function
    main().catch((err) => {
        console.log("Error occurred: ", err);
        process.exit(1);
     });    
    
  3. Reemplace <SERVICE BUS NAMESPACE CONNECTION STRING> por la cadena de conexión al espacio de nombres.

  4. Reemplace <TOPIC NAME> por el nombre del tema.

  5. Reemplace <SUBSCRIPTION NAME> por el nombre de la suscripción al tema.

  6. Después, ejecute el comando en un símbolo del sistema para ejecutar este archivo.

    node receivefromsubscription.js
    
  7. Debería ver la siguiente salida.

    Received message: Albert Einstein
    Received message: Werner Heisenberg
    Received message: Marie Curie
    Received message: Steven Hawking
    Received message: Isaac Newton
    Received message: Niels Bohr
    Received message: Michael Faraday
    Received message: Galileo Galilei
    Received message: Johannes Kepler
    Received message: Nikolaus Kopernikus
    

En Azure Portal, vaya al espacio de nombres de Service Bus y seleccione el tema en el panel inferior para ver la página Tema de Service Bus de su tema. En esta página debería ver tres mensajes entrantes y tres salientes en el gráfico Mensajes.

Mensajes entrantes y salientes

Si ejecuta solo la aplicación de envío la próxima vez, en la página Tema de Service Bus, verá seis mensajes entrantes (3 nuevos) pero tres mensajes salientes.

Página del tema actualizado

En esta página, si selecciona una suscripción, irá a la página Service Bus Subscription (Suscripción de Service Bus). En esta página puede ver el recuento de mensajes activos, el de mensajes con problemas de entrega y mucho más. En este ejemplo hay tres mensajes activos que todavía no ha recibido ningún receptor.

Recuento de mensajes activos

Pasos siguientes

Consulte la documentación y los ejemplos siguientes: