微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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>;
}

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

 

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐