Sobes.tech
Middle

What is a bus in the context of software development?

sobes.tech AI

Answer from AI

A bus is a software template or component that provides a unified mechanism for exchanging messages or events between different parts of a system or separate services.

Main types of buses:

  • Event Bus (Event Emitter): Allows components to subscribe to specific events and receive notifications when these events occur, regardless of the event initiator.
  • Command Bus: Used to send command objects to specific handlers, encapsulating the intention to perform a certain action.
  • Message Bus: A more general term that can include both events and commands, or be used as a message broker for asynchronous communication.

Examples of usage in Node.js:

  • Within an application for interaction between modules.
    const { EventEmitter } = require('events');
    
    const eventBus = new EventEmitter();
    
    eventBus.on('userCreated', (userData) => {
      console.log('New user created:', userData);
    });
    
    // Another module
    function createUser(data) {
      // User creation logic
      eventBus.emit('userCreated', data); // Emit event
    }
    
  • Between microservices using message brokers (such as Kafka, RabbitMQ).
    const amqp = require('amqplib');
    
    async function sendMessage() {
      const connection = await amqp.connect('amqp://localhost');
      const channel = await connection.createChannel();
      const queue = 'my_queue';
      const msg = 'Hello, world!';
    
      await channel.assertQueue(queue, { durable: false });
      channel.sendToQueue(queue, Buffer.from(msg));
      console.log('Sent message:', msg);
    
      setTimeout(() => {
        connection.close();
      }, 500);
    }
    
    sendMessage();