Microservices with NestJS
Build scalable, maintainable microservices using NestJS framework.
Project Setup
npm i -g @nestjs/cli
nest new user-service
cd user-service
npm install @nestjs/microservices
Creating a Microservice
// main.ts
import { NestFactory } from '@nestjs/core';
import { Transport, MicroserviceOptions } from '@nestjs/microservices';
async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
transport: Transport.RMQ,
options: {
urls: ['amqp://localhost:5672'],
queue: 'users_queue',
},
},
);
await app.listen();
}
bootstrap();
Message Patterns
// users.controller.ts
@Controller()
export class UsersController {
@MessagePattern({ cmd: 'get_user' })
getUser(@Payload() data: { id: number }) {
return this.usersService.findOne(data.id);
}
@EventPattern('user_created')
handleUserCreated(@Payload() data: User) {
this.analyticsService.trackUserCreation(data);
}
}
API Gateway
// gateway/users.controller.ts
@Controller('users')
export class UsersController {
constructor(
@Inject('USER_SERVICE') private client: ClientProxy,
) {}
@Get(':id')
async getUser(@Param('id') id: number) {
return this.client.send({ cmd: 'get_user' }, { id });
}
}
Service Discovery with Consul
// Register service on startup
const consul = new Consul();
await consul.agent.service.register({
name: 'user-service',
address: 'localhost',
port: 3001,
check: { http: 'http://localhost:3001/health', interval: '10s' },
});
NestJS provides excellent patterns for building enterprise-grade microservices.
Comments (0)
Leave a Comment
No comments yet. Be the first to share your thoughts!