Nacos Spring Cloud 配置笔记

178 阅读1分钟

安装

测试用途,使用docker 安装,后续会考虑使用k8s安装

git clone https://github.com/nacos-group/nacos-docker.git
cd nacos-docker
# 单机模式 derby
docker-compose -f example/standalone-derby.yaml up
# 单机模式 MySQL
docker-compose -f example/standalone-mysql-5.7.yaml up
docker-compose -f example/standalone-mysql-8.yaml up

使用

nacos 配置

命名空间
    -新建命名空间
  • 进入 配置管理--> 配置列表
    • 选择刚才创建的命名空间 ae
    • 选择导入配置
    • 将打包成zip格式的 yml配置文件导入到当前命名空间

Spring Cloud 程序配置

  1. 添加maven依赖,其中:
    • 1.5.x <--> Springboot 1.5.x
    • 2.1.x <--> Springboot 2.1.x
    • 2.0.x <--> Springboot 2.0.x
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
    <version>1.5.1.RELEASE</version>
</dependency>
  1. 修改bootstrap.yml
spring:
  application:
    name: notification-service
  cloud:
    nacos:
      config:
        server-addr: 10.92.104.160:8848 # nacos Server 地址
        namespace: d52cf1b0-be6b-42e9-87bb-97cd92850949 # namespace id 
        file-extension: yml
        group: ${spring.profiles.active}
        ext-config: # 共享application 配置文件
          - dataId: application.yml
            group: ${spring.profiles.active}
            refresh: true
  profiles:
    active: k8s-dev

在 Nacos Spring Cloud 中,dataId 的完整格式如下:

${prefix}-${spring.profiles.active}.${file-extension}
  • prefix 默认为 spring.application.name 的值,也可以通过配置项 spring.cloud.nacos.config.prefix来配置。

  • spring.profiles.active 即为当前环境对应的 profile,详情可以参考 Spring Boot文档。 注意:当 spring.profiles.active 为空时,对应的连接符 - 也将不存在,dataId 的拼接格式变成 ${prefix}.${file-extension}

  • file-exetension 为配置内容的数据格式,可以通过配置项 spring.cloud.nacos.config.file-extension 来配置。目前只支持 propertiesyaml 类型。