nestjs typescript grpc server服务端Demo(终于通了)
作者:互联网
试的想哭终于通了
-
目录结构 主要就是图里圈出来的四个文件
-
server的实现
-
proto文件
-
启动类main.ts
-
组件配置 app.modules.ts
-
依赖
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"
}
- main.ts 启动类 启动app
切记:配置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();
- main.module.ts 模型注册类
@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 {}
- proto文件
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;
}
- MarketDataGrpcController server服务实现类 Controller
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"}
}
}
- 启动的时候会提示找不到proto文件,你把proto文件复制到提示的那个dist生成的代码对应的文件夹下面去这样就能找到了,我是手动复制过去的
有问题再留言把
标签:typescript,proto,grpc,Demo,app,nestjs,import,data 来源: https://blog.51cto.com/humorchen/2984230