NestJS的微服务

NestJS官网对其微服务的定义:
In Nest, a microservice is fundamentally an application that uses a different transport layer than HTTP.
一个不使用HTTP作为传输层协议的App,就叫微服务。

这对于微服务的描述有点偏差,但不管怎么说,先按照教程实现一个demo。
npm i -g @nestjs/cli
nest new rocket-app
cd rocket-app
npm i --save @nestjs/core@latest @nestjs/common@latest
npm run start
访问 localhost:3000, 出现Hello World!

cd src && mkdir Rocket && cd Rocket
nest generate service Rocket --flat
nest generate controller Rocket –flat

修改app.module.ts

import { Module, HttpModule } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { RocketService } from './Rocket/rocket.service';
import { RocketController } from './Rocket/rocket.controller';

@Module({
  imports: [HttpModule],
  controllers: [AppController, RocketController],
  providers: [AppService, RocketService],
})
export class AppModule {}

rocket.service.ts

import { Injectable, HttpService } from '@nestjs/common';
import { map } from 'rxjs/operators';

@Injectable()
export class RocketService {
  constructor(private http: HttpService) {}

  getNextLaunchRemainingTime() {
    return this.http.get('https://api.spacexdata.com/v4/launches/next').pipe(
      map((response) => response.data),
      map((launch) => launch.date_utc),
    );
  }
}

Rocket.controller.ts

import { Controller, Get } from '@nestjs/common';
import { RocketService } from './rocket.service';

@Controller('rocket')
export class RocketController {
  constructor(private rocketService: RocketService) {}

  @Get('next-launch')
  getNextLaunchRemainingTime() {
    return this.rocketService.getNextLaunchRemainingTime();
  }
}

访问:http://localhost:3000/rocket/next-launch

现在准备转换为微服务的架构
npm i --save @nestjs/microservices
修改main.ts

import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';

async function bootstrap() {
  const app = await NestFactory.createMicroservice(
    AppModule,
    {
      transport: Transport.TCP,
      options: {
        host: '127.0.0.1',
        port: 8877,
      },
    },
  );
  app.listen(
    () => console.log(
      'Microservice is listening on port 8877'
    ));
}
bootstrap();

修改Rocket.controller.ts

import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
import { Observable } from 'rxjs';
import { RocketService } from './rocket.service';

@Controller('rocket')
export class RocketController {

  constructor(private rocketService: RocketService) { }

  @MessagePattern('get-next-launch-remaining-time')
  getNextLaunchRemainingTime(): Observable<string> {
    return this.rocketService.getNextLaunchRemainingTime();
  }

}

下面准备建立Client App
nest new rocket-client
npm i --save @nestjs/microservices
cd src && mkdir Rocket && cd Rocket
nest generate service Rocket --flat
nest generate controller Rocket –flat

rocket.service.ts

import { Injectable } from '@nestjs/common';
import { ClientProxyFactory, Transport, ClientProxy } from '@nestjs/microservices';

@Injectable()
export class RocketService {
  client: ClientProxy;

  constructor() {
    this.client = ClientProxyFactory.create({
      transport: Transport.TCP,
      options: {
        host: '127.0.0.1',
        port: 8877,
      },
    });
  }

  getNextLaunchRemainingTime() {
    return this.client
      .send<string, string>(
        'get-next-launch-remaining-time', '',
      );
  }
}

Rocket.controller.ts

import { Controller, Get } from '@nestjs/common';
import { RocketService } from './rocket.service';

@Controller('rocket')
export class RocketController {
  constructor(private rocketService: RocketService) {}

  @Get('next-launch')
  getNextLaunchRemainingTime() {
    return this.rocketService.getNextLaunchRemainingTime();
  }
}

分别启动服务端和client端, npm run start
访问:http://localhost:3000/rocket/next-launch

源码链接

posted @   老胡Andy  阅读(1420)  评论(0编辑  收藏  举报
编辑推荐:
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
阅读排行:
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具
点击右上角即可分享
微信分享提示