博客
关于我
Nacos做配置中心使用
阅读量:789 次
发布时间:2023-02-13

本文共 2502 字,大约阅读时间需要 8 分钟。

Nacos 配置中心实践指南

一、Nacos 作为配置中心的应用

在 app-user 服务中使用 Nacos 作为配置中心,实现外部化配置管理。

1. 引入依赖

在项目中添加 Nacos 配置中心的依赖项:

com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-config

2. 配置 Nacos 服务器地址

bootstrap.properties 文件中添加 Nacos 服务器地址及相关信息:

spring.cloud.nacos.config.server-addr=192.168.xxx.xxx:8848spring.cloud.nacos.config.username=nacosspring.cloud.nacos.config.password=nacosspring.cloud.nacos.config.namespace=b4d0832b-a7b0-44c2-8ce5-1abe676a4736

3. 配置 DataId 格式

Nacos 的 DataId 格式为:

${prefix}-${spring.profiles.active}.${file-extension}

其中:

  • prefix:默认为 spring.application.name,可通过 spring.cloud.nacos.config.prefix 配置。
  • spring.profiles.active:表示当前环境对应的 profile。
  • file-extension:配置文件的扩展名,可通过 spring.cloud.nacos.config.file-extension 配置,默认为 properties

application.yaml 中配置应用信息:

server:  port: 18081  servlet:    context-path: /app-userspring:  application:    name: app-user

4. 在 Nacos 服务器管理界面中添加配置

在 Nacos 服务器界面中,创建 DataId 为 app-user 的配置文件。

5. 测试配置信息获取

在启动类中使用 Spring 原生注解或 @RefreshScope 动态感知配置:

@SpringBootApplication@RefreshScopepublic class AppUserApplication {    public static void main(String[] args) throws InterruptedException {        ConfigurableApplicationContext applicationContext = SpringApplication.run(AppUserApplication.class, args);        while (true) {            String userName = applicationContext.getEnvironment().getProperty("user.name");            String userAge = applicationContext.getEnvironment().getProperty("user.age");            System.err.println("用户信息:name=" + userName + ", age=" + userAge);            TimeUnit.SECONDS.sleep(1);        }    }}

6. 配置 profile 粒度

通过 spring.profiles.active 配置多个环境下的配置:

application.yaml 中:

spring:  profiles:    active: dev

在 Nacos 服务器中创建对应的 DataId 配置文件,如 app-user-dev.yaml

7. 自定义 Namespace 和 Group

bootstrap.properties 中配置自定义 Namespace:

spring.cloud.nacos.config.namespace=b4d0832b-a7b0-44c2-8ce5-1abe676a4736

bootstrap.properties 中配置自定义 Group:

spring.cloud.nacos.config.group=DEVELOP_GROUP

8. 配置扩展的 DataId

支持多个配置文件共享或扩展:

spring.cloud.nacos.config.sharedConfigs:  - data-id: app.service.common01.yaml    refresh: true  - data-id: app.service.common02.yaml    refresh: truespring.cloud.nacos.config.extensionConfigs:  - data-id: app.service.common02.yaml    refresh: true

9. 配置优先级

配置优先级从高到低为:

  • spring.application.name - {spring.profiles.active}
  • spring.application.name.{spring.profiles.active}.{file-extension}
  • spring.application.name
  • 扩展配置(extensionConfigs)
  • 共享配置(sharedConfigs)
  • 优先级高的配置会覆盖优先级低的配置。

    转载地址:http://kgdfk.baihongyu.com/

    你可能感兴趣的文章