nacos通過api,讀取和發佈配置中心配置文件
String writerUrl = "http://127.0.0.1:8848/nacos/v1/cs/configs"
Map<String, String> param = new HashMap<>(6);
// 租戶信息,對應 Nacos 的命名空間ID字段。
param.put("tenant", "namespace");
param.put("dataId", dataId);
param.put("group", group);
// 配置類型
param.put("type", "properties");
// 配置內容,讀取配置的時候可以不要該參數
param.put("content", "XXXX");
try {
// 讀取配置用GET方法
String s = HttpUtils.requestGet(writerUrl, param, null);
System.out.println(s);
// 寫入配置,發佈配置,用POST方法
String s = HttpUtils.requestGet(writerUrl, param, null);
System.out.println(s);
} catch (RemoteServiceException e) {
e.printStackTrace();
}
以上的是看到別人寫的。
以下是我自己集成的代碼片段。springboot
public static final String SERVER_ADDR = "127.0.0.1:8848";
public static final String TEST_NAMESPACE = "5f86c5a7-3bf1-4108-966f-c25ebebf7803";
@GetMapping("getCityCodeListByNacosFactory")
public String getCityCodeListByNacosFactory() {
Properties properties = new Properties();
// nacos服務器地址,127.0.0.1:8848
properties.put(PropertyKeyConst.SERVER_ADDR, SERVER_ADDR);
// 配置中心的命名空間id
// properties.put(PropertyKeyConst.NAMESPACE, TEST_NAMESPACE);
ConfigService configService = null;
String content = "";
try {
configService = NacosFactory.createConfigService(properties);
// 根據dataId、group定位到具體配置文件,獲取其內容. 方法中的三個參數分別是: dataId, group, 超時時間
content = configService.getConfig("bamboo.test1", "DEFAULT_GROUP", 3000L);
// 因爲我的配置內容是JSON數組字符串,這裏將字符串轉爲JSON數組
System.out.println(content+"---------");
//寫入配置文件
configService.publishConfig("bamboo.test1", "DEFAULT_GROUP",content);
} catch (NacosException e) {
e.printStackTrace();
}
return content;
}
<!-- https://mvnrepository.com/artifact/com.alibaba.boot/nacos-config-spring-boot-starter -->
<dependency>
<groupId>com.alibaba.boot</groupId>
<artifactId>nacos-config-spring-boot-starter</artifactId>
<version>0.2.1</version>
</dependency>
nacos代碼:https://my.oschina.net/u/3730149/blog/4961453
解決問題:
運維部署發佈項目,配置不一致問題。這裏需要在程序調nacos的配置修改或者查詢操作。這樣操作不用讓運維手動在nacos修改配置和導入配置文件,減少錯誤率。其他第三方框架也可以借鑑這種解決方法,尤其是分佈式項目。