1

使用 Dapr JS SDK 让 Nest.js 集成 Dapr - 为少

 1 year ago
source link: https://www.cnblogs.com/hacker-linner/p/16387754.html
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

image

Dapr 是一个可移植的、事件驱动的运行时,它使任何开发人员能够轻松构建出弹性的、无状态和有状态的应用程序,并可运行在云平台或边缘计算中,它同时也支持多种编程语言和开发框架。

Dapr 中文手册:https://docs.dapr.io/zh-hans/

Dapr JS SDK

创建包含我们的 NestJS 项目的文件结构:

src/
    main.ts             
    app.module.ts       
    config/config.ts    
    dapr/
        dapr.module.ts  
        dapr.service.ts 

创建 Nest Dapr 模块

创建文件结构后,我们可以配置我们的模块并使其可用于 NestJS

src/dapr/dapr.module.ts

import { Module } from "@nestjs/common";
import { ConfigModule } from "@nestjs/config";
import { DaprService } from "./dapr.service";

@Module({
    imports: [ ConfigModule ],
    controllers: [ ],
    providers: [ DaprService ],
    exports: [ DaprService ]
})
export class DaprModule {}

上面的代码将利用 Config 模块(我们稍后将使用它来将配置注入我们的服务)以及我们将创建的包含 Dapr JS SDK 方法的 Dapr 服务。

最后,在 app.module.ts 文件中注册这个模块:

import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import configuration from '../config/config';
import { DaprModule } from './dapr/dapr.module';

@Module({
  imports: [
    ConfigModule.forRoot({
      load: [configuration],
    }),
    DaprModule
  ],
  controllers: [],
  providers: [],
})
export class AppModule;

src/dapr/dapr.service.ts

现在我们已经注册了我们的模块,让我们创建帮助我们访问 Dapr JS SDK 的服务类:

import { Injectable, Logger } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { DaprClient } from 'dapr-client';

@Injectable()
export class DaprService {
  daprClient: DaprClient;
  private readonly logger = new Logger(DaprService.name);

  constructor(
    private readonly configService: ConfigService
  ) {
    const daprHost = this.configService.get<string>('third_party.dapr.host');
    const daprPort = this.configService.get<string>('third_party.dapr.port');

    this.logger.log(`Initializing DaprClient("${daprHost}", ${daprPort})`);
    this.daprClient = new DaprClient(daprHost, daprPort);
  }
}

如您所见,我们在此处访问 third_party.dapr.hostthird_party.dapr.port,它们从 config/config.ts 文件中提取信息。所以继续使用以下配置:

export default () => ({
  third_party: {
    dapr: {
      host: process.env.DAPR_SIDECAR_HOST || '127.0.0.1',
      port: process.env.DAPR_SIDECAR_PORT || '3500',
    }
  },
});

使用 Nest 模块

现在我们创建了我们的模块,我们可以将它导入到我们的任何 Nest 模块中(在 imports: [ DaprModule ]下添加它)并开始使用它。

import { Controller, Get, HttpCode, Req, Logger } from '@nestjs/common';
import { ApiTags } from '@nestjs/swagger';
import { DaprService } from '../dapr/dapr.service';

@Controller('demo')
@ApiTags('demo')
export class DemoController {
  private readonly logger = new Logger(DemoController.name);

  constructor(
    private readonly daprService: DaprService,
  ) { }

  @Get('/')
  @HttpCode(200)
  async demo(@Req() req): Promise<void> {
    await this.daprService.daprClient.binding.send(`my-component`, "create", { hello: "world" });
 }

使用 Dapr 启动 Nest

为了开始这一切,我们现在可以使用 dapr run 命令,它会在其中创建包含 Dapr 的进程。

dapr run --app-id my-application --app-protocol http --app-port 50001 --dapr-http-port 3500 --components-path ./components npm run start

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK