node.js - 使用 nodeJS 应用程序调用我的 NestJs 微服务
问题描述
我想我可以说我对微服务有点菜鸟。所以,这就是我想玩它的原因。我使用了 NestJs,因为它看起来很简单
首先,我创建了一个新应用程序,nest new myservice
然后我从微服务文档中复制了示例main.ts
和 controller.ts 到项目中:
main.ts
:
import { NestFactory } from '@nestjs/core';
import { Transport } from '@nestjs/microservices';
import { AppModule } from './app.module';
async function bootstrap() {
const app = await NestFactory.createMicroservice(AppModule, {
transport: Transport.TCP,
options: { host: 'localhost', port: 3005 },
});
app.listen(() => console.log('Microservice is listening'));
}
bootstrap();
app.module.ts
import { Module } from '@nestjs/common';
import { AppController } from './app.controller';
import { AppService } from './app.service';
@Module({
imports: [],
controllers: [AppController],
providers: [AppService],
})
export class AppModule {
controoler.ts
import { Controller } from '@nestjs/common';
import { MessagePattern } from '@nestjs/microservices';
@Controller()
export class AppController {
@MessagePattern({ cmd: 'sum' })
accumulate(data: number[]): number {
return (data || []).reduce((a, b) => a + b);
}
}
现在,当我启动它时,一切看起来都很好:
✗ yarn start
yarn run v1.13.0
$ ts-node -r tsconfig-paths/register src/main.ts
[Nest] 45783 - 05/01/2019, 11:08 PM [NestFactory] Starting Nest application...
[Nest] 45783 - 05/01/2019, 11:08 PM [InstanceLoader] AppModule dependencies initialized +17ms
[Nest] 45783 - 05/01/2019, 11:08 PM [NestMicroservice] Nest
microservice successfully started
Microservice is listening
所以,如果这里有什么问题,请告诉我!但是知道我想编写一个可以调用/与这个微服务通信的小型测试 nodejs 应用程序。任何建议从哪里开始。例如,我可以使用 axios 还是应该使用其他东西。任何帮助,将不胜感激!
解决方案
您需要执行以下操作。
import { ClientTCP } from '@nestjs/microservices';
(async () => {
const client = new ClientTCP({
host: 'localhost',
port: 3005,
});
await client.connect();
const pattern = { cmd: 'sum' };
const data = [2, 3, 4, 5];
const result = await client.send(pattern, data).toPromise();
console.log(result);
})();
推荐阅读
- php - SetDrawColor() 的行为类似于 SetFillColor()
- scala - Scala为类型分配动态值
- c# - C# Entity Framework 在此上下文中仅支持原始类型或枚举类型
- html - 两个 html 部分之间的差距
- c# - 如果值在 oracle 查询中重复,如何取正确的值
- c++ - aarch64-linux-android-g++ 找不到导出的函数
- git - Git子模块恢复提交
- angular - 角事件发射器不工作
- html - 我的 HTML 页面的一部分必须滚动
- c# - ItemsControl 内 TexBox 中的 MouseBinding 不起作用 WPF C#