[Nodejs实战]3-连接nacos配置中心

453 阅读1分钟

一般后端项目都需要配置中心,以koa+nacos为例,

1.从nacos获取配置

import {NacosConfigClient} from 'nacos'
const configClient = new NacosConfigClient({
  serverAddr: nacos_serverAddr,
  namespace:nacos_namespace
});

2.编写koa中间件,将配置赋值全局变量

申明全局变量

declare global{
  namespace NodeJS{
    interface Global{
      config1,
      config2
    }
  }
}

启动文件(index.ts)中编写koa中间件

app.use(async (ctx, next)=>{
  const content= await configClient.getConfig(dataid, group);
  const r = YAML.parse(content);
  global.config1 = r.xxx;
  global.config2 = r.xxx;
  next();
})

说明:

  • 因为nacos配置的是yaml文件格式,引入YAML文件解析。
  • 其中 next()表示顺序执行,如果是await next() 表示其他中间件执行完了再执行这个中间件