我想我可以说我对微服务有些菜鸟。所以,这就是为什么我想玩它。我使用了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还是应该使用其他东西。任何帮助将不胜感激!
答案 0 :(得分:2)
您需要执行以下操作。
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);
})();