其他分享
首页 > 其他分享> > nestjs typescript grpc server服务端Demo(终于通了)

nestjs typescript grpc server服务端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"
  }

切记:配置url的时候用了localhost连接也需要用localhost,建议用IP
下面代码里http会在4001端口上跑,grpc会在4000上跑

import { join } from 'path';
import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { MicroserviceOptions, Transport } from '@nestjs/microservices';

async function bootstrap() {
  const app = await NestFactory.create(AppModule);
  app.connectMicroservice<MicroserviceOptions>({
    transport: Transport.GRPC,
    options: {
      package: 'market_data_collector',
      url: '192.168.0.140:4000',
      protoPath: join(__dirname, 'proto/MarketData.proto'),
    }});
  await app.startAllMicroservicesAsync();
  await app.listen(4001)
}
bootstrap();
@Module({
  imports: [
    //放mongo db地址  'mongodb://root:root@192.168.0.159:27017/quantitative_trading?authSource=admin',
    MongooseModule.forRoot('mongodb://root:root@192.168.0.159:27017/quantitative_trading?authSource=admin'),
    //注册所有的schema
    MongooseModule.forFeature([]),
  ],
  //GRCP Server 的Controller
  controllers: [ MarketDataGrpcController],
  providers: [],
})
export class AppModule {}
syntax = "proto3";
option java_multiple_files = true;
option java_package = "com.company.market_data_collector";
option java_outer_classname = "MarketData";
option objc_class_prefix = "company";

package market_data_collector;

service MarketDataService{
    //订阅
    rpc PushMarketData(PushMarketDataReq) returns( MarketDataRet);
}
//订阅行情数据请求
message PushMarketDataReq{
    string data=1;
}

//订阅行情数据响应
message MarketDataRet{
    string data=1;
}
import { Controller } from '@nestjs/common';
import { GrpcMethod } from '@nestjs/microservices';

/**
 * GRPC 服务器 用来接收价格通知 还有
 * */

interface PushMarketDataReq {
  data:string
}
interface PushMarketDataRet {
  data:string
}
@Controller()
export class MarketDataGrpcController {
  constructor() {}

  //第一个是servicename 第二个是函数名,请求和响应用interface包装
  @GrpcMethod('MarketDataService','PushMarketData')
  pushMarketData(data:PushMarketDataReq):PushMarketDataRet {
    console.log('收到请求');
    console.log(data);
    return {data:"1"}
  }
}

有问题再留言把

 

标签:typescript,proto,grpc,Demo,app,nestjs,import,data
来源: https://blog.51cto.com/humorchen/2984230