Dapr 是一個(gè)可移植的、事件驅(qū)動(dòng)的運(yùn)行時(shí),它使任何開發(fā)人員能夠輕松構(gòu)建出彈性的、無狀態(tài)和有狀態(tài)的應(yīng)用程序,并可運(yùn)行在云平臺(tái)或邊緣計(jì)算中,它同時(shí)也支持多種編程語言和開發(fā)框架。
Dapr 中文手冊(cè):https://docs.dapr.io/zh-hans/
文件結(jié)構(gòu)
Dapr JS SDK
- https://github.com/dapr/js-sdk
創(chuàng)建包含我們的 NestJS 項(xiàng)目的文件結(jié)構(gòu):
src/ main.ts app.module.ts config/config.ts dapr/ dapr.module.ts dapr.service.ts
創(chuàng)建 Nest Dapr 模塊
創(chuàng)建文件結(jié)構(gòu)后,我們可以配置我們的模塊并使其可用于 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 模塊(我們稍后將使用它來將配置注入我們的服務(wù))以及我們將創(chuàng)建的包含 Dapr JS SDK 方法的 Dapr 服務(wù)。
最后,在 app.module.ts 文件中注冊(cè)這個(gè)模塊:
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
現(xiàn)在我們已經(jīng)注冊(cè)了我們的模塊,讓我們創(chuàng)建幫助我們?cè)L問 Dapr JS SDK 的服務(wù)類:
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(‘third_party.dapr.host’); const daprPort = this.configService.get(‘third_party.dapr.port’); this.logger.log(`Initializing DaprClient(“${daprHost}”, ${daprPort})`); this.daprClient = new DaprClient(daprHost, daprPort); }}
如您所見,我們?cè)诖颂幵L問 third_party.dapr.host 和 third_party.dapr.port,它們從 config/config.ts 文件中提取信息。所以繼續(xù)使用以下配置:
export default () => ({ third_party: { dapr: { host: process.env.DAPR_SIDECAR_HOST || ‘127.0.0.1’, port: process.env.DAPR_SIDECAR_PORT || ‘3500’, } },});
使用 Nest 模塊
現(xiàn)在我們創(chuàng)建了我們的模塊,我們可以將它導(dǎo)入到我們的任何 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 { await this.daprService.daprClient.binding.send(`my-component`, “create”, { hello: “world” }); }
使用 Dapr 啟動(dòng) Nest
為了開始這一切,我們現(xiàn)在可以使用 dapr run 命令,它會(huì)在其中創(chuàng)建包含 Dapr 的進(jìn)程。
dapr run –app-id my-application –app-protocol http –app-port 50001 –dapr-http-port 3500 –components-path ./components npm run start