Exframe Messaging Queue

5.2.0 · active · verified Sun Apr 19

exframe-mq is a messaging framework module providing a simplified abstraction layer over RabbitMQ for Node.js applications, currently stable at version 5.2.0. It is part of the broader exframe ecosystem and is typically used in conjunction with other exframe-* packages like exframe-context, exframe-health, and exframe-logger. The library primarily focuses on a Publish/Subscribe topology, makes a key assumption of JSON payloads for all messages, and manages persistent and shared connections to the RabbitMQ server. While a specific release cadence isn't detailed, its close ties to other exframe modules suggest coordinated releases. Key differentiators include its opinionated, simplified API for common RabbitMQ patterns and deep integration with the exframe application framework.

Common errors

Warnings

Install

Imports

Quickstart

This example demonstrates how to initialize the `exframe-mq` module, configure a connection to RabbitMQ, create a messaging client, and then subscribe to and publish messages using a topic exchange topology.

import mq from 'exframe-mq'; // Use 'const mq = require("exframe-mq");' for CommonJS

// Mock a logger for demonstration purposes
const logger = {
  info: (message, ...args) => console.log('INFO:', message, ...args),
  error: (message, ...args) => console.error('ERROR:', message, ...args),
  warn: (message, ...args) => console.warn('WARN:', message, ...args),
  debug: (message, ...args) => console.debug('DEBUG:', message, ...args),
};

async function runMessagingExample() {
  const rabbitmqUrl = process.env.RABBITMQ_URL ?? 'amqp://localhost';

  console.log(`Attempting to connect to RabbitMQ at ${rabbitmqUrl}...`);

  try {
    // Initialize the main exframe-mq client
    const mqClient = mq.create({
      logger,
      url: rabbitmqUrl,
      heartbeat: 30,
      baseTimeout: 500,
      maxAttempts: 5,
      responseTimeout: 60 * 1000,
    });

    // Get a messaging client instance for publish/subscribe operations
    const client = mqClient.client();

    const EXCHANGE_NAME = 'my-app-exchange';
    const ROUTING_KEY_PATTERN = 'my.topic.#'; // Subscribe to all messages under 'my.topic'
    const PUBLISH_ROUTING_KEY = 'my.topic.hello';

    // Subscribe to messages on a topic exchange
    await client.subscribe(EXCHANGE_NAME, ROUTING_KEY_PATTERN, async (context, message, extraParams = {}) => {
      logger.info(`Received message: ${JSON.stringify(message)} with context ${JSON.stringify(context)} and extraParams ${JSON.stringify(extraParams)}`);
      // Simulate some asynchronous processing
      await new Promise(resolve => setTimeout(resolve, 100));
    }, { exchangeType: 'topic' });

    logger.info(`Successfully subscribed to '${EXCHANGE_NAME}' with routing key pattern '${ROUTING_KEY_PATTERN}'.`);

    // Publish a message after a short delay to allow subscription to establish
    setTimeout(() => {
      const messagePayload = { sender: 'quickstart-app', content: 'Hello from exframe-mq!' };
      logger.info(`Publishing message '${JSON.stringify(messagePayload)}' to '${EXCHANGE_NAME}' with routing key '${PUBLISH_ROUTING_KEY}'.`);
      client.publish(EXCHANGE_NAME, PUBLISH_ROUTING_KEY, messagePayload);
    }, 2000);

    console.log('Application running. Awaiting messages. Press Ctrl+C to exit.');
  } catch (error) {
    logger.error('Failed to initialize or connect to RabbitMQ:', error);
    process.exit(1);
  }
}

runMessagingExample();

view raw JSON →