完整示例代码参考:nacos-spring-boot-config-example
一、下载 Nacos 并启动 Nacos server。参考 Nacos快速开始
二、添加坐标 可参考 mvnrepository
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>${latest.version}</version>
</dependency>
三、在 application.properties
中配置 Nacos server 的地址:
nacos.config.server-addr=127.0.0.1:8848
四、使用 @NacosPropertySource注解配置Nacos
@SpringBootApplication
//加载 dataId 为 example 的配置源, 并开启自动更新
@NacosPropertySource(dataId = "example", autoRefreshed = true)
public class NacosConfigApplication {
public static void main(String[] args) {
SpringApplication.run(NacosConfigApplication.class, args);
}
}
五、通过 Nacos 的 @NacosValue
注解设置属性值。
@Controller
@RequestMapping("config")
public class ConfigController {
@NacosValue(value = "${useLocalCache:false}", autoRefreshed = true)
private boolean useLocalCache;
@RequestMapping(value = "/get", method = GET)
@ResponseBody
public boolean get() {
return useLocalCache;
}
}
六、
curl http://localhost:8080/config/get
output:
false
七、发布配置
// 通过调用 Nacos Open API 向 Nacos server 发布配置
// dataId 为example,内容为useLocalCache=true
curl -X POST "http://127.0.0.1:8848/nacos/v1/cs/configs?dataId=example&group=DEFAULT_GROUP&content=useLocalCache=true"
八、
// 再次访问 http://localhost:8080/config/get
curl http://localhost:8080/config/get
output:
true