ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

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

2021-07-05 18:05:53  阅读:247  来源: 互联网

标签:typescript service proto grpc Demo 7.6 nestjs hello


  • 依赖

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 文件
    在这里插入图片描述
  • 定义接口
import { Observable } from 'rxjs';

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

  • app.modules.ts 组件配置类

在这里插入图片描述

	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:[]里头注册一下
在这里插入图片描述
同时在这个service里来调用grpc的函数,返回结果,由于默认是Observable我们调用toPromise()变为promise的,被我包装成了service下的hello函数
在这里插入图片描述

@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来使用。

 

标签:typescript,service,proto,grpc,Demo,7.6,nestjs,hello
来源: https://blog.51cto.com/humorchen/2984226

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有