配置管理Nacos-config

Nacos 可以实现分布式环境下的配置管理。

前提条件

需要先下载 Nacos 并启动 Nacos server。

启动配置管理

1.添加依赖:


    org.springframework.boot
    spring-boot-starter


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

2.新建bootstrap.properties

在 bootstrap.properties 中配置 Nacos server 的地址和应用名

spring.cloud.nacos.config.server-addr=127.0.0.1:8848
spring.application.name=example
spring.cloud.nacos.config.file-extension=yaml

在 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 来配置。目前只支持 properties 和 yaml 类型。

3.编写Controller获取配置信息

启动类

package com.cloud.config;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class ConfigApplication {

    public static void main(String[] args) {
        SpringApplication.run(ConfigApplication.class, args);
    }

}

Controller

package com.cloud.config.controller;

import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequestMapping("/config")
@RefreshScope
public class ConfigController {

    @Value("${user.name}")
    private String name;

    @RequestMapping("/get")
    public String get() {
        return name;
    }
}

@RefreshScope会动态实时刷新配置信息,不需要重新启动程序。

4.在Nacos server上添加对象配置

配置Data Id为example.yaml


image.png
image.png

配置内容为:

spring:
  application:
    name: example
  cloud:
    nacos:
      discovery:
        server-addr: 127.0.0.1:8848

server:
  port: 7998

user:
  name: blue

5.启动ConfigApplication

访问 http://localhost:7998/config/get

image.png

此时会获取到Nacos server上的配置信息。

至此,动态获取配置完成。

你可能感兴趣的:(配置管理Nacos-config)