whale-nest-nacos
Version:
If you are a nest micro service architecture, you can use the SDK, so as to realize service discovery based on nacos, distributed load balancing strategy
70 lines • 3.06 kB
JavaScript
;
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
return new (P || (P = Promise))(function (resolve, reject) {
function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
step((generator = generator.apply(thisArg, _arguments || [])).next());
});
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.NacosConfigService = void 0;
const WhaleNacosClient_1 = require("../baseNacos/WhaleNacosClient");
const constant_1 = require("../constant");
const log_1 = require("../nacosLogger/log");
class NacosConfigService {
constructor({ group, serviceName, }) {
this.group = group || constant_1.DEFAULT_CONFIG_GROUP;
this.serviceName = serviceName;
this.nacosClientInstance = new WhaleNacosClient_1.WhaleNacosClient({
serverAddress: constant_1.serverAddress,
namespace: constant_1.namespace,
endpoint: '7777',
logger: log_1.logger
});
}
ready() {
return __awaiter(this, void 0, void 0, function* () {
const { nacosConfigClient } = yield this.nacosClientInstance.ready();
this.nacosConfigClient = nacosConfigClient;
yield this.getConfig();
});
}
// 从配置获取ip(请求地址)
getConfig(service) {
var _a;
return __awaiter(this, void 0, void 0, function* () {
const serviceName = service || this.serviceName;
// 订阅配置变更
this.subscribe();
const config = yield ((_a = this.nacosConfigClient) === null || _a === void 0 ? void 0 : _a.getConfig(serviceName, this.group));
if (!config) {
throw new Error(`未找到服务名为‘${serviceName}’的配置,请确认nacos是否存在该服务配置或服务名是否正确`);
}
this.config = config;
});
}
subscribe() {
var _a;
// listen data changed
(_a = this.nacosConfigClient) === null || _a === void 0 ? void 0 : _a.subscribe({
dataId: this.serviceName,
group: this.group,
}, (content) => {
if (content) {
this.config = content;
(0, log_1.log)(`配置订阅:`, {
dataId: this.serviceName,
group: this.group,
content
});
}
else {
throw new Error(`服务‘${this.serviceName}’的配置不存在,请确认`);
}
});
}
}
exports.NacosConfigService = NacosConfigService;
//# sourceMappingURL=index.js.map