SpringCloud应用集成Nacos配置中心

发布时间 2023-11-19 15:13:47作者: 安浩阳

SpringCloud应用集成Nacos配置中心

官方文档

第一步:引入依赖

版本见 => 附录:根pom文件=>版本控制片段


        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
        </dependency>

第二步:配置 application.yml 文件

spring:
   config:
    import:
      - nacos:nacos-config-example.properties # “nacos-config-example.properties” 是nacos配置中心的DataId
  cloud:
    nacos:
      config:
        server-addr: 127.0.0.1:8848 #nacos配置中心地址

Nacos中心配置如下

image

第三步:在应用中使用

package com.anhaoyang.test;

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

@RestController
@RefreshScope //该注解可使属性的在运行时自动刷新(即应用在运行中,nacos发布配置后,value值也是最新的)
public class NacosConfigController {
@Value("${test}")
private String value;

@GetMapping(&quot;/value&quot;)
public String getValue() {
    return value;
}

}

第四步:验证

(1)查询值

image

(2)在nacos中修改配置,并发布

image

(3)再次查询

image