当前位置: 首页> 文旅> 艺术 > Nestjs微服务简单案例

Nestjs微服务简单案例

时间:2025/7/9 21:17:08来源:https://blog.csdn.net/weixin_63443072/article/details/142049572 浏览次数:0次

相信大家,来看这篇博客,就应该知道微服务的概念。只是不太知道实用方法而已。下面我通过最简单的案例,来教会大家。

首先这是我的项目目录:

nestwfw/
├── app/
├── project-microserices

app 是web服务,用来接收前端请求的网络请求

project-microserices 是一个微服务,名字都是随意的

安装

nest new app
nest new project-microservices

 逻辑代码

1.首先编写微服务的代码,再去到web服务中去注册调用。所以我们先写project-microservices。

// project-microservices/main.tsimport { NestFactory } from '@nestjs/core';
import { Transport, MicroserviceOptions } from '@nestjs/microservices';
import { AppModule } from './app.module';async function bootstrap() {const app = await NestFactory.createMicroservice<MicroserviceOptions>(AppModule,{transport: Transport.TCP,options: {host: '127.0.0.1',port: 3001,}},);await app.listen();
}
bootstrap();
// project-microservices/app.controller.tsimport { Controller, Get } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
import { AppService } from './app.service';@Controller()
export class AppController {constructor(private readonly appService: AppService) { }@MessagePattern('project:computedCount')computedCount(data: { num1: number, num2: number }): number {return this.appService.computedCount(data.num1, data.num2);}
}
// project-microservices/app.service.ts
import { Injectable } from '@nestjs/common';@Injectable()
export class AppService {computedCount(num1: number, num2: number): number {console.log('project被调用来了')return num1 + num2;}
}

修改完这三出,你的一个微服务就横空出世了,接下来再去web服务中去调用即可。

2.在web服务中注册并使用

注册微服务,需要去app.module.ts中进行注册。

// app/app.module.tsimport { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
import { ClientsModule, Transport } from '@nestjs/microservices';@Module({imports: [ClientsModule.register([{name: 'PRODUCT_SERVICE',transport: Transport.TCP,options: {host: '127.0.0.1',port: 3001}}])],controllers: [AppController],providers: [AppService],
})
export class AppModule { }

注册完之后,可以去使用了。

// app/app.controller.tsimport { Controller, Get, Inject, Query } from '@nestjs/common';
import { AppService } from './app.service';
import { ClientProxy } from '@nestjs/microservices';@Controller()
export class AppController {constructor(private readonly appService: AppService,@Inject('PRODUCT_SERVICE') private client: ClientProxy) { }@Get('/count')computeCount(@Query() query: { num1: number, num2: number }) {console.log(query)return this.client.send('project:computedCount', query)}
}

这样,就是一个最简单的微服务案例。如果大家还是有不懂可以自行百度或者留下评论。

关键字:Nestjs微服务简单案例

版权声明:

本网仅为发布的内容提供存储空间,不对发表、转载的内容提供任何形式的保证。凡本网注明“来源:XXX网络”的作品,均转载自其它媒体,著作权归作者所有,商业转载请联系作者获得授权,非商业转载请注明出处。

我们尊重并感谢每一位作者,均已注明文章来源和作者。如因作品内容、版权或其它问题,请及时与我们联系,联系邮箱:809451989@qq.com,投稿邮箱:809451989@qq.com

责任编辑: