nestjs配置nacos
时间: 2023-12-01 07:43:01 浏览: 76
在NestJS中使用Nacos进行配置管理的步骤如下:
1. 安装nacos-sdk-nodejs
```shell
npm install nacos-sdk-nodejs --save
```
2. 在app.module.ts中引入ConfigModule
```typescript
import { Module } from '@nestjs/common';
import { ConfigModule } from '@nestjs/config';
import { NacosConfig } from 'nacos';
@Module({
imports: [
ConfigModule.forRoot({
isGlobal: true,
load: [],
expandVariables: true,
cache: true,
ignoreEnvFile: true,
load: [() => ({
nacos: {
host: 'localhost',
port: 8848,
namespace: 'public',
dataId: 'nest-config',
group: 'DEFAULT_GROUP',
},
})],
}),
],
})
export class AppModule {}
```
3. 创建一个config.service.ts文件
```typescript
import { Injectable } from '@nestjs/common';
import { ConfigService } from '@nestjs/config';
import { NacosConfigClient } from 'nacos';
@Injectable()
export class NacosConfigService {
private nacosConfigClient: NacosConfigClient;
constructor(private readonly configService: ConfigService) {
const nacosConfig = this.configService.get('nacos');
this.nacosConfigClient = new NacosConfigClient({
serverAddr: `${nacosConfig.host}:${nacosConfig.port}`,
namespace: nacosConfig.namespace,
});
}
async get(key: string): Promise<string> {
return await this.nacosConfigClient.getConfig(nacosConfig.dataId, nacosConfig.group);
}
}
```
4. 在需要使用配置的地方注入NacosConfigService
```typescript
import { Injectable } from '@nestjs/common';
import { NacosConfigService } from './config.service';
@Injectable()
export class AppService {
constructor(private readonly configService: NacosConfigService) {}
async getHello(): Promise<string> {
const value = await this.configService.get('key');
return `Hello ${value}!`;
}
}
```
阅读全文