1. NestJS のマイクロサービス
NestJS は、マイクロサービスの多くのトランスポート層をサポートしています。
- TCP: 組み込み、シンプル、内部サービスに使用
- レディス: Pub/Sub パターン
- RabbitMQ (AMQP): 強力なメッセージキュー
- gRPC: 高性能 RPC フレームワーク
- カフカ: イベントストリーミングプラットフォーム
npm install @nestjs/microservices
2. TCPトランスポート
// Microservice (User Service) — main.ts
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
UserModule,
{
transport: Transport.TCP,
options: { host: '0.0.0.0', port: 3001 },
},
);
await app.listen();
// User Service — Controller
import { MessagePattern, Payload } from '@nestjs/microservices';
@Controller()
export class UserController {
@MessagePattern({ cmd: 'get_user' })
getUser(@Payload() data: { id: string }) {
return this.usersService.findById(data.id);
}
@MessagePattern({ cmd: 'create_user' })
createUser(@Payload() data: CreateUserDto) {
return this.usersService.create(data);
}
}
// API Gateway — gọi microservice
@Module({
imports: [
ClientsModule.register([{
name: 'USER_SERVICE',
transport: Transport.TCP,
options: { host: 'user-service', port: 3001 },
}]),
],
})
export class AppModule {}
// Gateway Controller
@Controller('users')
export class UsersController {
constructor(@Inject('USER_SERVICE') private userClient: ClientProxy) {}
@Get(':id')
getUser(@Param('id') id: string) {
return this.userClient.send({ cmd: 'get_user' }, { id });
}
}
3. RabbitMQ トランスポート
npm install amqplib amqp-connection-manager
// Order Service — main.ts
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
OrderModule,
{
transport: Transport.RMQ,
options: {
urls: [process.env.RABBITMQ_URL],
queue: 'orders_queue',
queueOptions: { durable: true },
},
},
);
// Event-based: Publish event
@Injectable()
export class OrderService {
constructor(@Inject('NOTIFICATION_SERVICE') private client: ClientProxy) {}
async createOrder(dto: CreateOrderDto) {
const order = await this.orderRepo.save(dto);
// Emit event (fire & forget)
this.client.emit('order_created', {
orderId: order.id,
userId: order.userId,
total: order.total,
});
return order;
}
}
// Notification Service — lắng nghe event
@Controller()
export class NotificationController {
@EventPattern('order_created')
handleOrderCreated(@Payload() data: OrderCreatedEvent) {
this.notificationService.sendOrderConfirmation(data);
}
}
4. gRPC トランスポート
npm install @grpc/grpc-js @grpc/proto-loader
// proto/user.proto
syntax = "proto3";
package user;
service UserService {
rpc FindOne (UserById) returns (User) {}
rpc FindAll (Empty) returns (Users) {}
}
message UserById {
string id = 1;
}
message User {
string id = 1;
string name = 2;
string email = 3;
}
message Users {
repeated User users = 1;
}
message Empty {}
// gRPC Microservice
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
UserModule,
{
transport: Transport.GRPC,
options: {
package: 'user',
protoPath: join(__dirname, 'proto/user.proto'),
url: '0.0.0.0:5000',
},
},
);
// gRPC Controller
@Controller()
export class UserController {
@GrpcMethod('UserService', 'FindOne')
findOne(data: { id: string }): User {
return this.usersService.findById(data.id);
}
@GrpcMethod('UserService', 'FindAll')
findAll(): { users: User[] } {
return { users: this.usersService.findAll() };
}
}
5. ハイブリッド アプリケーション (HTTP + マイクロサービス)
// main.ts — vừa HTTP vừa microservice
const app = await NestFactory.create(AppModule);
// Kết nối thêm microservice transport
app.connectMicroservice<MicroserviceOptions>({
transport: Transport.RMQ,
options: {
urls: [process.env.RABBITMQ_URL],
queue: 'orders_queue',
},
});
await app.startAllMicroservices();
await app.listen(3000);
6. まとめ
- メッセージパターン: リクエスト-レスポンス(送信/受信)
- イベントパターン: Fire-and-forget イベント (発行/リッスン)
- TCP: シンプルな内部サービス
- ラビットMQ: 信頼性の高いメッセージング、配信不能キュー
- gRPC: 高性能、強力な型指定
- ハイブリッド: 同じアプリ内の HTTP + マイクロサービス
次の記事で詳しく説明します NestJS でのテスト。