代码

代码地址

https://gitee.com/zjj19941/ZJJ_Neaten5.10/tree/master/ZJJ_Nacos/nacos-spring-boot-config-example

从官网弄来的,自己简单改了改 ,很简单的案例,

pom依赖

  1. <properties>
  2. <nacos-config-spring-boot.version>0.2.1</nacos-config-spring-boot.version>
  3. </properties>
  4. <dependencies>
  5. <dependency>
  6. <groupId>org.springframework.boot</groupId>
  7. <artifactId>spring-boot-starter-web</artifactId>
  8. </dependency>
  9. <dependency>
  10. <groupId>org.springframework.boot</groupId>
  11. <artifactId>spring-boot-starter-actuator</artifactId>
  12. </dependency>
  13. <dependency>
  14. <groupId>com.alibaba.boot</groupId>
  15. <artifactId>nacos-config-spring-boot-starter</artifactId>
  16. <version>${nacos-config-spring-boot.version}</version>
  17. </dependency>
  18. <dependency>
  19. <groupId>com.alibaba.boot</groupId>
  20. <artifactId>nacos-config-spring-boot-actuator</artifactId>
  21. <version>${nacos-config-spring-boot.version}</version>
  22. </dependency>
  23. </dependencies>

application.properties

server.port=8080
nacos.config.server-addr=zjj101:8848

启动类


import com.alibaba.nacos.spring.context.annotation.config.NacosPropertySource;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

/**
 * Nacos 控制台添加配置:
 * Data ID:example
 * Group:DEFAULT_GROUP
 * 配置内容:useLocalCache=true
 */
@SpringBootApplication
//指定nacos配置资源是 example
//autoRefreshed = true 代表自动刷新
@NacosPropertySource(dataId = "example", autoRefreshed = true)
public class NacosConfigApplication {

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

controller


@Controller
@RequestMapping("config")
public class ConfigController {

    @NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
    private boolean useLocalCache;

    /**
     * 访问: localhost:8080/config/get
     */
    @RequestMapping(value = "/get", method = GET)
    @ResponseBody
    public boolean get() {
        return useLocalCache;
    }
}

nacos配置

useLocalCache: true

image.png

测试

postman调用接口: get请求 localhost:8080/config/get 即可看到效果

你在nacos-server修改完了之后,再访问上面的接口就能看到最新的内容了