@inest/nestjs-nacos
v2.0.2
Published
基于Nestjs集成Nacos,实现配置中心、服务发现等功能
Downloads
62
Maintainers
Readme
@inest/nestjs-nacos
nestjs-nacos 是基于 NestJS 的 Nacos 客户端模块。它可以帮助你在 NestJS 应用中轻松使用 Nacos 进行服务发现和配置管理。
安装
npm i @inest/nestjs-nacos
yarn add @inest/nestjs-nacos
pnpm i @inest/nestjs-nacos
使用
配置中心
@Module({
imports: [
// 导入nacos模块
NacosConfigModule.forRoot({
serverAddr: SERVER_ADDR,
namespace: NAMESPACE,
isPrintLog: true, // 是否打印日志
}),
// 异步导入nacos模块
/*NacosConfigModule.forRootAsync({
isGlobal: true,
inject: [XXXService],
useFactory: (service: XXXService) => {
// 读取本地配置:.yml、.evn、.properties等
const config = service.getConfig();
return {
serverAddr: config.serverAddr,
namespace: config.namespace,
isPrintLog: true, // 是否打印日志
};
},
}),*/
],
controllers: [AppController],
providers: [AppService],
})
export class AppModule implements OnModuleInit {
// 注入configClient,用于对配置的操作
@ConfigClient()
client: NacosConfigClient;
// 注入要监听的dataId
@Config('test')
private config: any;
// 默认情况下:{ group:'DEFAULT_GROUP', parser: 转成json }
@Config('test1', {
group: 'TEST', parser: (config) => {
// 转换config
try {
return JSON.parse(config);
} catch (e) {
return config;
}
},
})
private config1: any;
async onModuleInit() {
// 加载config配置是异步的,在模块初始化时,可能还没有设置值
setTimeout(() => {
console.info(this.config);
console.info(this.config1);
}, 1000);
}
}
NacosConfigClient用法参考官方API