其他分享
首页 > 其他分享> > nestjs typescript grpc client客户端Demo(终于通了)

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"
  }
import { Observable } from 'rxjs';

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

在这里插入图片描述

	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需要在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