整合步驟
- 1 pom.xml引入依賴
注意:版本 0.2.x.RELEASE 對應(yīng)的是 Spring Boot 2.x 版本,版本 0.1.x.RELEASE 對應(yīng)的是 Spring Boot 1.x 版本焰情。
<!-- 這里的的springboot使用的是2.2.6.RELEASE -->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.1</version>
</dependency>
- 2 application.properties配置文件中添加
#nacos地址 ip:port, 例如127.0.0.1:8848
nacos.config.server-addr=ip:port
- 3 springboot的啟動類上添加注解
@NacosPropertySource(dataId = "dataId", autoRefreshed = true)
- 4 簡單使用(兩步)
a.nacos控制臺中添加配置(Properties配置格式)
b.通過@NacosValue(value = "${config}", autoRefreshed = true)
注解使用
使用樣例
nacos中的配置內(nèi)容(properties配置格式)
city={"001":{"cityName":"shanghai","cityUrl":"www"},"002":{"cityName":"niuyue","cityUrl":"xxx"},"003":{"cityName":"shouer","cityUrl":"yyy","cityNull":"null"}}
啟動類
@SpringBootApplication
@NacosPropertySource(dataId = "dataId", autoRefreshed = true)
public class DemoNacosApplication {
public static void main(String[] args) {
SpringApplication.run(DemoNacosApplication.class, args);
}
model實體類
public class CityInfo {
private String cityName;
private String cityUrl;
// get,set,toString
}
controller
@RestController
@RequestMapping("/config")
public class NacosTestController {
@NacosValue(value = "${city}", autoRefreshed = true)
private String city;
@GetMapping("nacos")
public Object getValues(String cityCode){
// 從nacos中獲取數(shù)據(jù) fastJson
JSONObject jsonObject = JSON.parseObject(city);
System.out.println("nacos-config:"+city);
// 根據(jù)key獲取對象
CityInfo info = jsonObject.getObject(cityCode, CityInfo.class);
System.out.println(cityCode+"的info:"+info);
return info;
}
}