用NodeJS应用调用我的NestJs微服务 [英] Call my NestJs microservice with nodeJS app

查看:0
本文介绍了用NodeJS应用调用我的NestJs微服务的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想我可以说我是微服务的新手。所以,这就是我想玩它的原因。我用的是NestJs,因为它看起来很简单

首先,我用nest new myservice创建了一个新应用 然后,我将示例main.ts和Controler.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);
})();

这篇关于用NodeJS应用调用我的NestJs微服务的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆