|
| 1 | +--- |
| 2 | +sidebar_position: 6 |
| 3 | +--- |
| 4 | + |
| 5 | +# AMQP Integration |
| 6 | + |
| 7 | +@rhtml provides AMQP (Advanced Message Queuing Protocol) integration through the `@rhtml/amqp` package, designed for seamless interaction with message brokers such as RabbitMQ. It allows developers to easily publish and subscribe to messages, integrating AMQP functionalities into their applications with minimal setup. |
| 8 | + |
| 9 | +## 🚀 Installation |
| 10 | + |
| 11 | +```bash |
| 12 | +npm install @rhtml/amqp |
| 13 | +``` |
| 14 | + |
| 15 | +## 🎯 Quick Start |
| 16 | + |
| 17 | +### Basic Configuration |
| 18 | + |
| 19 | +You can set up the AMQP connection in your application by using the `AmqpModule.forRoot` method. This allows you to configure the connection settings such as protocol, hostname, port, credentials, and vhost. |
| 20 | + |
| 21 | +```typescript |
| 22 | +import { FastifyModule } from '@rhtml/fastify'; |
| 23 | +import { AmqpModule } from '@rhtml/amqp'; |
| 24 | + |
| 25 | +@Module({ |
| 26 | + imports: [ |
| 27 | + FastifyModule.forRoot(), |
| 28 | + AmqpModule.forRoot({ |
| 29 | + protocol: 'amqp', |
| 30 | + hostname: 'localhost', |
| 31 | + port: 5672, |
| 32 | + username: 'guest', |
| 33 | + password: 'guest', |
| 34 | + vhost: '/', |
| 35 | + }), |
| 36 | + ], |
| 37 | +}) |
| 38 | +export class AppModule {} |
| 39 | +``` |
| 40 | + |
| 41 | +### Environment Configuration |
| 42 | + |
| 43 | +Set your AMQP connection details in your environment variables: |
| 44 | + |
| 45 | +```bash |
| 46 | +# .env file |
| 47 | +AMQP_PROTOCOL=amqp |
| 48 | +AMQP_HOSTNAME=localhost |
| 49 | +AMQP_PORT=5672 |
| 50 | +AMQP_USERNAME=guest |
| 51 | +AMQP_PASSWORD=guest |
| 52 | +AMQP_VHOST=/ |
| 53 | +``` |
| 54 | + |
| 55 | +### Usage with Environment Variables |
| 56 | + |
| 57 | +```typescript |
| 58 | +import { Module } from '@rhtml/di'; |
| 59 | +import { AmqpModule } from '@rhtml/amqp'; |
| 60 | + |
| 61 | +@Module({ |
| 62 | + imports: [ |
| 63 | + AmqpModule.forRoot({ |
| 64 | + protocol: process.env.AMQP_PROTOCOL || 'amqp', |
| 65 | + hostname: process.env.AMQP_HOSTNAME || 'localhost', |
| 66 | + port: parseInt(process.env.AMQP_PORT || '5672'), |
| 67 | + username: process.env.AMQP_USERNAME || 'guest', |
| 68 | + password: process.env.AMQP_PASSWORD || 'guest', |
| 69 | + vhost: process.env.AMQP_VHOST || '/', |
| 70 | + }), |
| 71 | + ], |
| 72 | +}) |
| 73 | +export class CoreModule {} |
| 74 | +``` |
| 75 | + |
| 76 | +## 📦 Package Information |
| 77 | + |
| 78 | +### Features |
| 79 | + |
| 80 | +- **AMQP Protocol Support**: Full support for AMQP protocol with customizable configurations |
| 81 | +- **Integration with Fastify**: Easily integrate AMQP with Fastify controllers and routes |
| 82 | +- **Simple Publish and Subscribe Mechanism**: Simplified API for sending and consuming messages |
| 83 | +- **Customizable Options**: Configure protocol, hostname, port, authentication, and vhost |
| 84 | +- **Channel Management**: Ability to specify different channels than the default one |
| 85 | +- **Error Handling**: Robust error handling when subscription fails to prevent application crashes |
| 86 | + |
| 87 | +### Package Structure |
| 88 | + |
| 89 | +```json |
| 90 | +{ |
| 91 | + "name": "@rhtml/amqp", |
| 92 | + "version": "0.0.134", |
| 93 | + "dependencies": { |
| 94 | + "@rhtml/di": "^0.0.132", |
| 95 | + "amqplib": "^0.10.3" |
| 96 | + } |
| 97 | +} |
| 98 | +``` |
| 99 | + |
| 100 | +## 🔧 Integration with @rhtml Framework |
| 101 | + |
| 102 | +### Module-based Architecture |
| 103 | + |
| 104 | +The AMQP integration follows the @rhtml module pattern: |
| 105 | + |
| 106 | +```typescript |
| 107 | +import { Module } from '@rhtml/di'; |
| 108 | +import { AmqpModule } from '@rhtml/amqp'; |
| 109 | + |
| 110 | +@Module({ |
| 111 | + imports: [ |
| 112 | + AmqpModule.forRoot({ |
| 113 | + protocol: 'amqp', |
| 114 | + hostname: 'localhost', |
| 115 | + port: 5672, |
| 116 | + username: 'guest', |
| 117 | + password: 'guest', |
| 118 | + vhost: '/', |
| 119 | + }), |
| 120 | + ], |
| 121 | + providers: [ |
| 122 | + // Your services that use AMQP |
| 123 | + ], |
| 124 | +}) |
| 125 | +export class AppModule {} |
| 126 | +``` |
| 127 | + |
| 128 | +### Service Integration |
| 129 | + |
| 130 | +Create services that use AMQP for message publishing and consumption: |
| 131 | + |
| 132 | +```typescript |
| 133 | +import { Injectable, Inject } from '@rhtml/di'; |
| 134 | +import { AmqpChannel, AmqpService, ConsumeMessage } from '@rhtml/amqp'; |
| 135 | + |
| 136 | +@Injectable() |
| 137 | +export class MessageService { |
| 138 | + constructor(private amqpService: AmqpService) {} |
| 139 | + |
| 140 | + async publish(name: string, payload: any) { |
| 141 | + await this.amqpService.publish(name, { |
| 142 | + payload: {}, |
| 143 | + }); |
| 144 | + } |
| 145 | +} |
| 146 | +``` |
| 147 | + |
| 148 | +### Controller Integration |
| 149 | + |
| 150 | +Use AMQP in your Fastify controllers: |
| 151 | + |
| 152 | +```typescript |
| 153 | +import { Controller, Route, Post, Body } from '@rhtml/fastify'; |
| 154 | +import { Injectable, Inject } from '@rhtml/di'; |
| 155 | +import { MessageService } from './message.service'; |
| 156 | + |
| 157 | +@Injectable() |
| 158 | +export class NotificationController { |
| 159 | + constructor(private messageService: MessageService) {} |
| 160 | + |
| 161 | + @Route({ |
| 162 | + url: '/publish-message', |
| 163 | + }) |
| 164 | + async sendNotification(notification: any) { |
| 165 | + await messageService.publish('my-message-queue', {}); |
| 166 | + } |
| 167 | + |
| 168 | + @Subscribe({ |
| 169 | + queue: 'my-message-queue', |
| 170 | + consumeOptions: { |
| 171 | + noAck: false, |
| 172 | + }, |
| 173 | + }) |
| 174 | + async myMessageQueueSubscription( |
| 175 | + message: ConsumeMessage, |
| 176 | + channel: AmqpChannel |
| 177 | + ) { |
| 178 | + // Handle subscription and manually set acknowledgment when message is consumed |
| 179 | + channel.ack(); |
| 180 | + } |
| 181 | + |
| 182 | + @Subscribe({ |
| 183 | + queue: 'my-message-queue', |
| 184 | + consumeOptions: { |
| 185 | + noAck: true, |
| 186 | + }, |
| 187 | + }) |
| 188 | + async myMessageQueueSubscription( |
| 189 | + message: ConsumeMessage, |
| 190 | + channel: AmqpChannel |
| 191 | + ) { |
| 192 | + // Auto acknowledgment when the message is received |
| 193 | + } |
| 194 | + |
| 195 | + @Subscribe({ |
| 196 | + queue: 'my-queue-with-custom-amqp-channel', |
| 197 | + consumeOptions: { |
| 198 | + noAck: false, |
| 199 | + }, |
| 200 | + channel: MyAmqpChannel, |
| 201 | + }) |
| 202 | + async myTestQueue(message: ConsumeMessage, channel: AmqpChannel) { |
| 203 | + console.log('[REQUEST_RECEIVED]', message); |
| 204 | + |
| 205 | + // LONG RUNNING JOB 5-10 minutes |
| 206 | + channel.ack(message); |
| 207 | + console.log('[REQUEST_ACKNOWLEDGED]'); |
| 208 | + await this.amqpService.publish( |
| 209 | + 'my-queue-with-custom-amqp-channel-ack', |
| 210 | + {}, |
| 211 | + { channel } |
| 212 | + ); |
| 213 | + console.log('[MESSAGE_ACKNOWLEDGED_SEND]'); |
| 214 | + } |
| 215 | +} |
| 216 | +``` |
| 217 | + |
| 218 | +## 🔄 Advanced Usage Patterns |
| 219 | + |
| 220 | +### Custom Channel Configuration |
| 221 | + |
| 222 | +You can specify different channels than the default one: |
| 223 | + |
| 224 | +```typescript |
| 225 | +import { Module, InjectionToken } from '@rhtml/di'; |
| 226 | +import { AmqpModule, AmqpConnection } from '@rhtml/amqp'; |
| 227 | + |
| 228 | +export const MyAmqpChannel = new InjectionToken<Channel>(); |
| 229 | +export type MyAmqpChannel = Channel; |
| 230 | + |
| 231 | +@Module({ |
| 232 | + imports: [ |
| 233 | + AmqpModule.forRoot({ |
| 234 | + protocol: 'amqp', |
| 235 | + hostname: 'localhost', |
| 236 | + port: 5672, |
| 237 | + username: 'guest', |
| 238 | + password: 'guest', |
| 239 | + vhost: '/', |
| 240 | + channel: 'custom-channel-name', |
| 241 | + }), |
| 242 | + ], |
| 243 | + providers: [ |
| 244 | + { |
| 245 | + provide: MyAmqpChannel, |
| 246 | + deps: [AmqpConnection], |
| 247 | + useFactory: async (connection: Connection) => { |
| 248 | + const channel = await connection.createChannel(); |
| 249 | + await retryable(channel, { |
| 250 | + initialDelay: 5000, |
| 251 | + maxRetries: 5, |
| 252 | + separator: '.', |
| 253 | + }); |
| 254 | + await channel.prefetch(1); |
| 255 | + return channel; |
| 256 | + }, |
| 257 | + }, |
| 258 | + ], |
| 259 | +}) |
| 260 | +export class AppModule {} |
| 261 | +``` |
| 262 | + |
| 263 | +## 🎯 Best Practices |
| 264 | + |
| 265 | +### 1. **Connection Management** |
| 266 | + |
| 267 | +- Use environment variables for connection configuration |
| 268 | +- Implement proper error handling for connection failures |
| 269 | +- Monitor connection status in production |
| 270 | +- Use connection pooling for high-throughput applications |
| 271 | + |
| 272 | +### 2. **Message Handling** |
| 273 | + |
| 274 | +- Always acknowledge messages after successful processing |
| 275 | +- Implement dead letter queues for failed messages |
| 276 | +- Use message persistence for critical messages |
| 277 | +- Implement retry logic for transient failures |
| 278 | + |
| 279 | +### 3. **Queue Design** |
| 280 | + |
| 281 | +- Use descriptive queue names |
| 282 | +- Implement proper queue durability |
| 283 | +- Use exchanges for complex routing patterns |
| 284 | +- Implement message TTL for time-sensitive messages |
| 285 | + |
| 286 | +### 4. **Performance Optimization** |
| 287 | + |
| 288 | +- Use prefetch limits to control message consumption |
| 289 | +- Implement message batching for high-throughput scenarios |
| 290 | +- Use connection pooling for multiple consumers |
| 291 | +- Monitor queue depths and processing times |
| 292 | + |
| 293 | +## 🚀 Next Steps |
| 294 | + |
| 295 | +- Learn about [Dependency Injection](/docs/getting-started/providers) for service management |
| 296 | +- Explore [Modules](/docs/getting-started/modules) for application organization |
| 297 | +- Check out [Controllers](/docs/getting-started/controllers) for API development |
| 298 | +- Understand [Testing Strategies](/docs/getting-started/testing) for message queue testing |
| 299 | +- Review [Performance Optimization](/docs/advanced/performance) for queue optimization |
0 commit comments