Nacos可作爲consul config作爲配置中心,Nacos 是支持熱加載的.
下面介紹springboot如何集成nacos作爲配置中心
1、添加依賴
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.1</version>
</dependency>
注意:版本 0.2.x.RELEASE 對應的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 對應的是 Spring Boot 1.x 版本。
2、在 application.properties 中配置 Nacos server 的地址:
spring.application.name=springboot2-nacos-config
nacos.config.server-addr=127.0.0.1:8848
server.port=8088
3、使用 @NacosPropertySource 加載 dataId 爲 springboot2-nacos-config 的配置源,並開啓自動更新
@SpringBootApplication
@RestController
@NacosPropertySource(dataId = "springboot2-nacos-config", autoRefreshed = true)
@RefreshScope
public class NacosApplication {
public static void main(String[] args) {
SpringApplication.run(NacosApplication.class, args);
}
4、通過 Nacos 的 @NacosValue 註解設置屬性值。
@NacosValue(value = "${nacos.test.propertie:123}",autoRefreshed = true)
private String testProperties;
5、啓動 NacosConfigApplication,調用:http://localhost:8088/test,返回內容是 123.
@GetMapping("/test")
public String test() {
return testProperties;
}
6、在nacos的控制檯http://127.0.0.1:8848/nacos/index.html.修改配置
7、再次調用:http://localhost:8088/test.可以看到返回的結果爲098.配置被動態更新了.