增加任务
This commit is contained in:
67
front-end/nacos-federation/src/nacosServiceManage.ts
Normal file
67
front-end/nacos-federation/src/nacosServiceManage.ts
Normal file
@@ -0,0 +1,67 @@
|
||||
import { NacosNamingClient } from 'nacos';
|
||||
// @ts-ignore
|
||||
import { formatServiceUrl, getLocalIP } from "./utils";
|
||||
|
||||
const logger = console;
|
||||
|
||||
|
||||
export interface RegisterOptions {
|
||||
serverList: string;
|
||||
/** 服务名称(如 'main-app') */
|
||||
serviceName: string;
|
||||
/** 服务端口号 */
|
||||
port: number;
|
||||
/** 命名空间(用于环境隔离,默认 'public') */
|
||||
namespace?: string;
|
||||
}
|
||||
|
||||
|
||||
export class nacosServiceManage {
|
||||
|
||||
public nacosClient!: NacosNamingClient;
|
||||
public initOptions!: RegisterOptions;
|
||||
|
||||
|
||||
constructor(option: RegisterOptions) {
|
||||
this.initOptions = option;
|
||||
this.init()
|
||||
}
|
||||
|
||||
|
||||
async init() {
|
||||
this.nacosClient = new NacosNamingClient({
|
||||
logger,
|
||||
serverList: this.initOptions.serverList,
|
||||
namespace: this.initOptions.namespace || 'public',
|
||||
});
|
||||
await this.nacosClient.ready();
|
||||
this.reg()
|
||||
}
|
||||
|
||||
/**
|
||||
* 注册服务到Nacos并返回客户端实例
|
||||
*/
|
||||
async reg() {
|
||||
const { serviceName, port } = this.initOptions;
|
||||
const ip = getLocalIP();
|
||||
// @ts-ignore
|
||||
await this.nacosClient.registerInstance(serviceName, {
|
||||
port, ip
|
||||
})
|
||||
console.log(`[nacos] 服务 ${ serviceName } 已注册:${ formatServiceUrl(ip, port) }`);
|
||||
}
|
||||
|
||||
/**
|
||||
* 从Nacos发现服务地址
|
||||
* @param serviceName 发现选项
|
||||
* @returns 服务地址(如 'http://192.168.1.101:1301')
|
||||
*/
|
||||
async find(serviceName: string) {
|
||||
const instances = await this.nacosClient.getAllInstances(serviceName);
|
||||
if (instances.length === 0) {
|
||||
throw new Error(`[nacos] 未发现服务 ${ serviceName } 的实例`);
|
||||
}
|
||||
return formatServiceUrl(instances[0].ip, instances[0].port);
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user