npm i --save @nestjs/microservices
npm i --save grpc @grpc/proto-loader
syntax = "proto3"; package first; // 包名 service CatsService { rpc FindOne (ById) returns (Cat) {} // 暴露方法 } // message定义结构 message ById { // 参数 int32 id = 1; } message Cat { // 返回类型 int32 id = 1; string name = 2; }
import { Transport, ClientOptions } from ‘@nestjs/microservices‘; import { join } from ‘path‘; export const grpcServerOptions: ClientOptions = { transport: Transport.GRPC, options: { url: ‘localhost:8888‘, // grpc连接ip与端口 package: ‘first‘, // 包名 与.proto中保持一致 protoPath: join(__dirname, ‘../cats.proto‘) // 找到cats.proto }, };
// 开启grpc 作为grpc服务 app.connectMicroservice(grpcServerOptions);// grpcServerOptions为3.2中的配置 app.startAllMicroservicesAsync()
import { Controller, Get, Param } from ‘@nestjs/common‘; import { AppService } from ‘./app.service‘; import { GrpcMethod } from ‘@nestjs/microservices‘ @Controller() export class AppController { constructor(private readonly appService: AppService) {} // @GrpcMethod(‘CatsService‘, ‘FindOne‘) // GrpcMethod中第一个是.proto中服务, 第二个参数是暴露方法名, 不写的话默认是方法的首字母大写 @GrpcMethod(‘CatsService‘, ‘FindOne‘) findOne (data: {id: number}, metdata: any) { const items = [ { id: 1, name: ‘John‘ }, { id: 2, name: ‘Doe‘ }, ]; return items.find( ({ id }) => id === data.id ); } @Get() getHello(): string { return this.appService.getHello(); } }
localhost:8888/first.CatsService/FindOne
import { Injectable } from "@nestjs/common"; import { ClientGrpc, Client } from "@nestjs/microservices"; import { Transport, ClientOptions } from ‘@nestjs/microservices‘; import { join } from ‘path‘; // 与服务端的options中配置一致 export const grpcClientOptions: ClientOptions = { transport: Transport.GRPC, options: {
}; @Injectable() export class ClentServe {
// 客户端 实例 使用@Client()装饰器 @Client(grpcClientOptions) public readonly client: ClientGrpc; }
import { Controller, Get, Post, Body, Inject, OnModuleInit } from ‘@nestjs/common‘; import { ApiOperation } from ‘@nestjs/swagger‘; import { CreateCatsDto } from ‘./dto/cat.dto‘; import { GrpcMethod } from ‘@nestjs/microservices‘; import { ClentServe } from ‘src/grpc-client/client.serve‘; import { CatsService } from ‘src/grpc-client/interface/api.interface‘; @Controller(‘cats‘) export class CatsController implements OnModuleInit { private catService constructor(@Inject(ClentServe) private readonly clentServe: ClentServe) {} onModuleInit() {
// 可以在程序中创建接口CatsService, 这样调用方法时方便,有提示, 没有也可以
// this.catService = this.clentServe.client.getService<CatsService>(‘CatsService‘) this.catService = this.clentServe.client.getService(‘CatsService‘) } @Get() index() { return this.catService.findOne({id: 2}) } @Post() createPosts (@Body() dto: CreateCatsDto) { return dto } }
原文:https://www.cnblogs.com/liangyy/p/11911626.html