nestjs typescript grpc client客户端Demo(终于通了)
  HJwyUgQ6jyHT 14天前 20 0
  • 依赖

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

【版权声明】本文内容来自摩杜云社区用户原创、第三方投稿、转载,内容版权归原作者所有。本网站的目的在于传递更多信息,不拥有版权,亦不承担相应法律责任。如果您发现本社区中有涉嫌抄袭的内容,欢迎发送邮件进行举报,并提供相关证据,一经查实,本社区将立刻删除涉嫌侵权内容,举报邮箱: cloudbbs@moduyun.com

  1. 分享:
最后一次编辑于 14天前 0

暂无评论

HJwyUgQ6jyHT