Node.js 集成 Nacos 实现 服务发现、配置管理

https://github.com/nacos-group/nacos-sdk-nodejs

npm install nacos --save

服务发现

'use strict';

const NacosNamingClient = require('nacos').NacosNamingClient;
const logger = console;

const client = new NacosNamingClient({
  logger,
  serverList: '127.0.0.1:8848', // replace to real nacos serverList
  namespace: 'public',
});
await client.ready();

const serviceName = 'nodejs.test.domain';

// registry instance
await client.registerInstance(serviceName, {
  ip: '1.1.1.1',
  port: 8080,
});
await client.registerInstance(serviceName, {
  ip: '2.2.2.2',
  port: 8080,
});

// subscribe instance
client.subscribe(serviceName, hosts => {
  console.log(hosts);
});

// deregister instance
await client.deregisterInstance(serviceName, {
  ip: '1.1.1.1',
  port: 8080,
});

配置中心

import {NacosConfigClient} from 'nacos';   // ts
const NacosConfigClient = require('nacos').NacosConfigClient; // js

// for find address mode
const configClient = new NacosConfigClient({
  endpoint: 'acm.aliyun.com',
  namespace: '***************',
  accessKey: '***************',
  secretKey: '***************',
  requestTimeout: 6000,
});

// for direct mode
const configClient = new NacosConfigClient({
  serverAddr: '127.0.0.1:8848',
});

// get config once
const content= await configClient.getConfig('test', 'DEFAULT_GROUP');
console.log('getConfig = ',content);

// listen data changed
configClient.subscribe({
  dataId: 'test',
  group: 'DEFAULT_GROUP',
}, content => {
  console.log(content);
});

// publish config
const content= await configClient.publishSingle('test', 'DEFAULT_GROUP', '测试');
console.log('getConfig = ',content);

// remove config
await configClient.remove('test', 'DEFAULT_GROUP');
作者:Jeebiz  创建时间:2023-02-27 18:14
最后编辑:Jeebiz  更新时间:2024-02-28 14:53