首页 > 解决方案 > 使用 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 还是应该使用其他东西。任何帮助,将不胜感激!

标签: node.jsmicroservicesnestjs

解决方案


您需要执行以下操作。

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

推荐阅读