nestjs typescript grpc client客户端Demo(终于通了)

  • 依赖

grpc和microserver的

{
    "@grpc/proto-loader": "^0.6.1",
    "@nestjs/common": "^7.6.15",
    "@nestjs/config": "^0.6.3",
    "@nestjs/core": "^7.6.15",
    "@nestjs/microservices": "^7.6.15",
    "@nestjs/mongoose": "^7.2.4",
    "@nestjs/platform-express": "^7.6.15",
    "@nestjs/schedule": "^0.4.3",
    "@types/cron": "^1.7.2",
    "cron": "^1.8.2",
    "fastq": "^1.11.0",
    "grpc": "^1.24.6",
    "nest-winston": "^1.4.0",
    "reflect-metadata": "^0.1.13",
    "rimraf": "^3.0.2",
    "rxjs": "^6.6.6",
    "schedule": "^0.5.0",
    "winston": "^3.3.3",
    "winston-daily-rotate-file": "^4.5.1"
  }
  • proto 文件
    nestjs typescript grpc client客户端Demo(终于通了)
  • 定义接口
import { Observable } from 'rxjs';

export interface StrategyGrpcService {
  hello(data: { message: string }): Observable<any>;
}

  • app.modules.ts 组件配置类

nestjs typescript grpc client客户端Demo(终于通了)

	ClientsModule.register([
      {
        //注入的时候需要用这个名字,随便取
        name: 'GrpcClient',
        transport: Transport.GRPC,
        options: {
          //和proto里的package要一样
          package: 'strategy',
          //server端的ip和地址
          url: '192.168.0.140:12300',
          //proto文件
          protoPath: join(__dirname, './grpc/Strategy.proto'),
        },
      },
    ]),
  • 定义service,给我们的service里里注入grpc客户端client和service

这个service需要在app.modules.ts的providers:[]里头注册一下
nestjs typescript grpc client客户端Demo(终于通了)
同时在这个service里来调用grpc的函数,返回结果,由于默认是Observable我们调用toPromise()变为promise的,被我包装成了service下的hello函数
nestjs typescript grpc client客户端Demo(终于通了)

@Injectable()
export class SubscribeStrategyService {
  //proto service
  private strategyGrpcService : StrategyGrpcService;

  constructor(
    @Inject('GrpcClient') private client: ClientGrpc,
  ) {}
  
  async hello(message: string): Promise<any> {
    console.log('发送');
    console.log(this.strategyGrpcService);
    try {
      return await this.strategyGrpcService.hello({ message: message }).toPromise();
    } catch (e) {
      console.log(e);
    }
  }
}

到此只需要调用这个SubscribeStrategyService的hello函数就可以了,你也可以直接去调用this.strategyGrpcService来使用。

 

上一篇:grpc(三)


下一篇:grpc(二)