CQRS based on RabbitMQ
CQRS in NestJS Using RabbitMQ
🧱 Why CQRS with Messaging?
🛠 Messaging Setup with RabbitMQ
@Module({})
export class MessagingWrapperModule {
static forRoot(enableConsumer: boolean): DynamicModule {
return {
imports: [
MessagingRabbitmqExtensionModule,
MessagingModule.forRoot({
buses: [
{ name: 'sync-command.bus', channels: ['sync-channel'] },
{ name: 'command.bus', channels: ['amqp-command.channel'] },
{ name: 'event.bus', channels: ['amqp-event.channel'] },
],
channels: [
new InMemoryChannelConfig({ name: 'sync-channel' }),
new AmqpChannelConfig({
name: 'amqp-command.channel',
connectionUri: 'amqp://guest:guest@localhost:5672/',
exchangeName: 'book_shop.exchange',
bindingKeys: ['book_shop.#'],
exchangeType: ExchangeType.TOPIC,
queue: 'book_shop.command',
autoCreate: true,
enableConsumer,
}),
new AmqpChannelConfig({
name: 'amqp-event.channel',
connectionUri: 'amqp://guest:guest@localhost:5672/',
exchangeName: 'book_shop.exchange',
bindingKeys: ['book_shop.#'],
exchangeType: ExchangeType.TOPIC,
queue: 'book_shop.event',
autoCreate: true,
enableConsumer,
}),
],
debug: true,
}),
],
providers: [
{
provide: Service.CommandBus,
useFactory: (bus: IMessageBus) => new InternalMessageBus(bus),
inject: ['command.bus'],
},
{
provide: Service.EventBus,
useFactory: (bus: IMessageBus) => new InternalMessageBus(bus),
inject: ['event.bus'],
},
{
provide: Service.SyncCommandBus,
useFactory: (bus: IMessageBus) => new InternalMessageBus(bus),
inject: ['sync-command.bus'],
},
],
exports: [
Service.CommandBus,
Service.EventBus,
Service.SyncCommandBus,
],
module: MessagingWrapperModule,
global: true,
};
}
}📦 InternalMessageBus Wrapper
🧩 Dependency Injection
✅ Example Usage
🧪 Final Thoughts
Last updated