nest使用grpc实现微服务
【摘要】 首先下载依赖 "@grpc/grpc-js": "^1.13.4", "@grpc/proto-loader": "^0.7.15", "@nestjs/common": "^11.0.1", "@nestjs/core": "^11.0.1", "@nestjs/microservices": "^11.0.1", "@nestjs/platform-e...
首先下载依赖
"@grpc/grpc-js": "^1.13.4",
"@grpc/proto-loader": "^0.7.15",
"@nestjs/common": "^11.0.1",
"@nestjs/core": "^11.0.1",
"@nestjs/microservices": "^11.0.1",
"@nestjs/platform-express": "^11.0.1",
"reflect-metadata": "^0.2.2",
"rxjs": "^7.8.1"
然后先新建一个proto文件
syntax="proto3";
package hello;
service HelloService{
rpc SayHello(HelloRequest)returns(HelloResponse){}
}
message HelloRequest{
string name=1;
}
message HelloResponse{
string message=1;
}
然后在main.ts中创建微服务
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';
async function bootstrap() {
const app = await NestFactory.createMicroservice<MicroserviceOptions>(
AppModule,
{
transport: Transport.GRPC,
options: {
url: '0.0.0.0:50051',
package: 'hello',
protoPath: 'hello.proto',
},
},
);
await app.listen();
}
bootstrap();
然后在controller中使用GrpcMethod装饰器装饰需要调用的方法
import { Controller, Get } from '@nestjs/common';
import { AppService } from './app.service';
import { GrpcMethod } from '@nestjs/microservices/decorators';
@Controller()
export class AppController {
constructor(private readonly appService: AppService) {}
@GrpcMethod('HelloService', 'SayHello')
getHello(data) {
console.log(data);
return { message: 'hello' };
}
}
至此服务端就写完了。
接下来是客户端,依赖也是相同的。
首先在app.module.ts中注册grpc服务
import { 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: 'HELLO',
transport: Transport.GRPC,
options: {
url: '0.0.0.0:50051',
package: 'hello',
protoPath: 'hello.proto',
},
},
]),
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {}
然后就可以在controller中注入service,service中再注入ClientGrpc的实例
import { Injectable, Inject } from '@nestjs/common';
import { ClientGrpc } from '@nestjs/microservices';
import { firstValueFrom } from 'rxjs';
interface HelloService {
SayHello(data: { name: string }): any;
}
@Injectable()
export class AppService {
constructor(@Inject('HELLO') private client: ClientGrpc) {}
onModuleInit() {}
getHello(): string {
let res = this.client
.getService<HelloService>('HelloService')
.SayHello({ name: 'cc' });
firstValueFrom(res).then((val) => {
console.log(val);
});
return 'Hello World!';
}
}
【声明】本内容来自华为云开发者社区博主,不代表华为云及华为云开发者社区的观点和立场。转载时必须标注文章的来源(华为云社区)、文章链接、文章作者等基本信息,否则作者和本社区有权追究责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱:
cloudbbs@huaweicloud.com
- 点赞
- 收藏
- 关注作者
评论(0)