Message Bus
π¬ MessageBus
The MessageBus
It is the core interface used to dispatch messages within your microservice architecture. It acts as the gateway between your application and the configured messaging channels, enabling seamless communication between services.
Whether you're calling from a controller, service, or any provider, the MessageBus
gives you a powerful and type-safe way to route and send messages through your event-driven system.
π What Is the MessageBus?
The MessageBus
is injected via the @MessageBus('bus.name')
decorator and gives you access to methods that allow you to:
Send messages to specific handlers via routing
Send raw or structured messages
Target a specific channel (e.g., in-memory, AMQP)
Trigger synchronous or asynchronous processing
π Injecting the MessageBus
When configuring your messaging module, you define named buses. To use a bus, inject it using its name.
Example
import { Controller, Get } from '@nestjs/common';
import { MessageBus, IMessageBus, RoutingMessage } from '@nestjstools/messaging';
import { SendMessage } from './messages/send-message';
@Controller()
export class AppController {
constructor(@MessageBus('message.bus') private readonly messageBus: IMessageBus) {}
@Get()
async dispatch(): Promise<string> {
await this.messageBus.dispatch(
new RoutingMessage(new SendMessage('Hello World!'), 'your.message'),
);
return 'Message dispatched!';
}
}
π§© RoutingMessage Structure
To route a message to the correct handler, use the RoutingMessage
class:
new RoutingMessage(payload: object, route: string, messageOptions?: MessageOptions)
Example:
new RoutingMessage(
new SendMessage('User created'),
'user.created',
);
π‘ Bus-to-Channel Mapping
In your configuration, each bus can be connected to multiple channels:
MessagingModule.forRoot({
buses: [
{
name: 'message.bus',
channels: ['my-channel'], // All messages from this bus go here
},
],
channels: [
new InMemoryChannelConfig({
name: 'my-channel',
}),
],
})
β A message dispatched from a bus is passed to each of its configured channels.
π One Bus, Many Channels
Each bus can dispatch to multiple channels, and you can even configure different channels (e.g., RabbitMQ + InMemory) to receive the same message for hybrid systems.
π Benefits of MessageBus
β Type-safe
Dispatch class-based messages with strict typing
π Pluggable
Supports multiple channels per bus
π‘ Scalable
Easily add more channels or handlers without changing your core logic
π§ͺ Testable
Easily mock or simulate dispatches in testing environments
Last updated