// nacos.service.ts import { Injectable, OnApplicationBootstrap, OnApplicationShutdown, } from '@nestjs/common'; import { ConfigService } from '@nestjs/config'; import { NacosConfigClient, NacosNamingClient } from 'nacos'; // ts import * as os from 'os'; @Injectable() export class NacosService implements OnApplicationBootstrap, OnApplicationShutdown { private nacosNamingClient: NacosNamingClient; private nacosConfigClient: NacosConfigClient; serviceName: string; instance: { ip: string; port: number }; group: string; dataId: string; constructor(private configService: ConfigService) { this.nacosNamingClient = new NacosNamingClient({ logger: console, serverList: configService.get('NACOS_ADDR'), namespace: configService.get('NACOS_NAMESPACE'), }); this.nacosConfigClient = new NacosConfigClient({ namespace: configService.get('NACOS_NAMESPACE'), serverAddr: configService.get('NACOS_ADDR'), }); this.serviceName = configService.get('NACOS_SERVICE_NAME'); this.dataId = configService.get('NACOS_DATAID'); this.group = configService.get('NACOS_GROUP'); this.instance = { ip: this.getServerIP(), port: configService.get('PORT'), }; } /** * nestjs应用被关闭前 * @param {string} signal 'SIGTERM' | 'SIGINT' | 'SIGHUP' | 'SIGBREAK' */ onApplicationShutdown(signal?: string) { if (signal) { const { serviceName, instance, group } = this; this.nacosNamingClient.deregisterInstance(serviceName, instance, group); this.nacosConfigClient.close(); } } /** * 应用完全启动&微服务也被成功启动 */ onApplicationBootstrap() { const { serviceName, instance } = this; this.nacosNamingClient.registerInstance(serviceName, instance); } /** * 先于 onApplicationBootstrap */ async onModuleInit() { this.nacosNamingClient.ready(); } /** * 从nacos获取最新的配置信息 */ async getConfig() { const { dataId, group } = this; const configFromNacos = await this.nacosConfigClient.getConfig( dataId, group, ); return configFromNacos; } /** * 订阅配置中心,当远程修改nacos的配置时,触发 */ async subscribeConfiguration() { const { dataId, group } = this; this.nacosConfigClient.subscribe( { dataId, group, }, (content) => console.log('content', content), ); } getServerIP(): string { const networkInterfaces = os.networkInterfaces(); for (const name of Object.keys(networkInterfaces)) { for (const iface of networkInterfaces[name]) { // 跳过IPv6和内部地址 if ('IPv4' !== iface.family || iface.internal !== false) { continue; } // 返回第一个找到的IPv4地址 return iface.address; } } return 'localhost'; // 如果找不到外部IPv4地址,返回localhost } }