Jea*_*eri 1 node.js microservices 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();
Run Code Online (Sandbox Code Playgroud)
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 {
Run Code Online (Sandbox Code Playgroud)
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);
}
}
Run Code Online (Sandbox Code Playgroud)
现在,当我启动它时,一切看起来都很好:
? 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
Run Code Online (Sandbox Code Playgroud)
所以,如果这里有什么问题,请告诉我!但是知道我想编写一个可以调用/与此微服务通信的小型测试 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);
})();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1556 次 |
| 最近记录: |