如何将 Nest.js 微服务拆分为单独的项目? [英] How to split Nest.js microservices into separate projects?

查看:64
本文介绍了如何将 Nest.js 微服务拆分为单独的项目?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

假设我想创建一个简单的电影管理平台.它只需要很少的微服务:moviescinemaspayments

Let's say I want to create a simplistic cinema-management platform. It needs few microservices: movies, cinemas, payments, etc.

你会如何在 Nest.js 中做到这一点?我不希望它们放在同一个大文件夹中,因为这感觉就像制作一个整体.我希望它们成为具有自己的 git 存储库的单独 Nest.js 项目,以便我稍后可以使用 Kubernetes 对它们进行编排.

How would you go about doing it in Nest.js? I don't want them in the same big folder as that feels like making a monolith. I want them to be separate Nest.js projects with their own git repositories so I can orchestrate them with Kubernetes later on.

怎么样?如果cinemas 服务是两个独立的项目并且只共享,例如Redis,如何从服务cinemas 连接到服务movies?

How? How to connect from service cinemas to service movies if they are two separate projects and only share, let's say, Redis?

这通常不是关于微服务的问题.这是一个 Nest.js 特有的问题.我阅读了文档,我知道有像 @Client 这样的装饰器可以连接到传输层.我只想知道在何处使用该装饰器,并且可能会看到一段关于拥有两个独立的 Nest.js 存储库如何将它们连接在一起以便它们可以相互通信"的简短代码片段.

This is not a question about microservices in general. This is a question Nest.js specific. I read the documentation, I know there are decorators like @Client for connecting to the transport layer. I just want to know where to use that decorator and maybe see a short snippet of code on "having two separate Nest.js repositories how to connect them together so they can talk to each other".

我不关心传输层,我可以自己弄清楚.我只需要一些关于框架本身的建议,因为我认为缺少文档.

I don't care about the transport layer, that thing I can figure out myself. I just need some advice on the framework itself as I believe the documentation is lacking.

推荐答案

我搞定了.基本上,这样做的方法是创建两个单独的项目.假设 - 一个是 createMicroservice 而另一个只是一个 HTTP 应用程序(但很容易成为另一个微服务).我使用了一个普通"的应用程序,以便我可以轻松调用它进行测试.

I got it working. Basically the way to do it is to create two separate projects. Let's say - one is a createMicroservice and another is just an HTTP app (but could easily be another microservice). I used a "normal" app just so I can call it easily for testing.

这是创建微服务的 main.ts 文件.

Here is the main.ts file that creates microservice.

import { NestFactory } from '@nestjs/core';
import { AppModule } from './app.module';
import { Transport } from '@nestjs/common/enums/transport.enum';

async function bootstrap() {
  const app = await NestFactory.createMicroservice(AppModule, {
    transport: Transport.REDIS,
    options: {
      url: 'redis://localhost:6379',
    },
  });
  await app.listen(() => console.log('MoviesService is running.'));
}
bootstrap();

和控制器之一:

@Controller()
export class AppController {
  constructor(private readonly appService: AppService) {}

  @MessagePattern({ cmd: 'LIST_MOVIES' })
  listMovies(): string[] {
    return ['Pulp Fiction', 'Blade Runner', 'Hatred'];
  }
}

现在 - 在微服务中,您声明控制器应对哪些类型的事件做出反应 (@MessagePattern).在普通"服务中,当您想向其他微服务询问某些内容时,您在控制器中执行此操作(main.ts 是您使用 @nestjs/cli.

Now - in the microservice you declare to what kinds of events should controllers react to (@MessagePattern). While in the "normal" service you do this in the controller when you want to ask other microservices for something (the main.ts is the simplest example that you get when you create a new project using @nestjs/cli.

控制器代码:

@Controller()
export class AppController {
  private readonly client: ClientProxy;

  constructor(private readonly appService: AppService) {
    this.client = ClientProxyFactory.create({
      transport: Transport.REDIS,
      options: {
        url: 'redis://localhost:6379',
      },
    });
  }

  @Get()
  listMovies() {
    const pattern = { cmd: 'LIST_MOVIES' };

    return this.client.send<string[]>(pattern, []);
  }
}

因此,只要 client 与微服务连接到相同的传输层,它们就可以使用 @MessagePattern 相互通信.

So as long a client is connected to the same transport layer as the microservice - they can talk to each other by using the @MessagePattern.

为了获得更好的代码,您可以将 this.client 部分从构造函数移动到提供程序,然后通过在模块中声明提供程序来使用依赖注入.

For nicer code you can move the this.client part from a constructor to a provider and then use dependency injection by declaring the provider in the module.

这篇关于如何将 Nest.js 微服务拆分为单独的项目?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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