1、pom.xml依赖
<dependencies>
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>fastjson</artifactId>
<version>1.2.62</version>
</dependency>
<dependency>
<groupId>org.apache.httpcomponents</groupId>
<artifactId>httpclient</artifactId>
<version>4.5.13</version>
</dependency>
<dependency>
<groupId>org.yaml</groupId>
<artifactId>snakeyaml</artifactId>
<version>1.27</version>
</dependency>
</dependencies>
2、HttpClientUtil.class工具类
package com.nacos.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.Consts;
import org.apache.http.HttpEntity;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpEntityEnclosingRequestBase;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.client.methods.HttpPut;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.util.EntityUtils;
import java.io.IOException;
import java.net.URI;
import java.util.*;
/**
* @author: zhaoxu
* @description:
*/
public class HttpClientUtil {
/**
* get请求,params可为null,headers可为null
*
* @param headers
* @param url
* @return
* @throws IOException
*/
public static String get(Map<String, String> headers, String url, JSONObject params) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建get请求
HttpGet httpGet = null;
List<BasicNameValuePair> paramList = new ArrayList();
if (params != null) {
Iterator<String> iterator = params.keySet().iterator();
while (iterator.hasNext()) {
String paramName = iterator.next();
paramList.add(new BasicNameValuePair(paramName, params.get(paramName).toString()));
}
}
httpGet = new HttpGet(url + "?" + EntityUtils.toString(new UrlEncodedFormEntity(paramList, Consts.UTF_8)));
if (headers != null) {
Iterator iterator = headers.keySet().iterator();
while (iterator.hasNext()) {
String headerName = iterator.next().toString();
httpGet.addHeader(headerName, headers.get(headerName));
}
}
httpGet.addHeader("Content-Type", "application/json");
// 从响应模型中获得具体的实体
HttpEntity entity = httpClient.execute(httpGet).getEntity();
String response = EntityUtils.toString(entity);
httpClient.close();
return response;
}
/**
* post请求,params可为null,headers可为null
*
* @param headers
* @param url
* @param params
* @return
* @throws IOException
*/
public static String post(Map<String, String> headers, String url, JSONObject params) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建post请求
HttpPost httpPost = new HttpPost(url);
if (headers != null) {
Iterator iterator = headers.keySet().iterator();
while (iterator.hasNext()) {
String headerName = iterator.next().toString();
httpPost.addHeader(headerName, headers.get(headerName));
}
}
httpPost.addHeader("Content-Type", "application/json");
if (params != null) {
StringEntity stringEntity = new StringEntity(params.toJSONString());
httpPost.setEntity(stringEntity);
}
// 从响应模型中获得具体的实体
HttpEntity entity = httpClient.execute(httpPost).getEntity();
String response = EntityUtils.toString(entity);
httpClient.close();
return response;
}
/**
* post请求,params可为null,headers可为null
*
* @param headers
* @param url
* @param params
* @return
* @throws IOException
*/
public static String postMap(Map<String, String> headers, URI url, JSONObject params) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建post请求
HttpPost httpPost = new HttpPost(url);
if (headers != null) {
Iterator iterator = headers.keySet().iterator();
while (iterator.hasNext()) {
String headerName = iterator.next().toString();
httpPost.addHeader(headerName, headers.get(headerName));
}
}
httpPost.addHeader("Content-Type", "application/json");
if (params != null) {
StringEntity stringEntity = new StringEntity(params.toJSONString());
httpPost.setEntity(stringEntity);
}
// 从响应模型中获得具体的实体
HttpEntity entity = httpClient.execute(httpPost).getEntity();
String response = EntityUtils.toString(entity);
httpClient.close();
return response;
}
/**
* delete,params可为null,headers可为null
*
* @param url
* @param params
* @return
* @throws IOException
*/
public static String delete(Map<String, String> headers, String url, JSONObject params) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建delete请求,HttpDeleteWithBody 为内部类,类在下面
HttpDeleteWithBody httpDelete = new HttpDeleteWithBody(url);
if (headers != null) {
Iterator iterator = headers.keySet().iterator();
while (iterator.hasNext()) {
String headerName = iterator.next().toString();
httpDelete.addHeader(headerName, headers.get(headerName));
}
}
httpDelete.addHeader("Content-Type", "application/json");
if (params != null) {
StringEntity stringEntity = new StringEntity(params.toJSONString());
httpDelete.setEntity(stringEntity);
}
// 从响应模型中获得具体的实体
HttpEntity entity = httpClient.execute(httpDelete).getEntity();
String response = EntityUtils.toString(entity);
httpClient.close();
return response;
}
/**
* put,params可为null,headers可为null
*
* @param url
* @param params
* @return
* @throws IOException
*/
public static String put(Map<String, String> headers, String url, JSONObject params) throws IOException {
CloseableHttpClient httpClient = HttpClientBuilder.create().build();
// 创建put请求
HttpPut httpPut = new HttpPut(url);
if (headers != null) {
Iterator iterator = headers.keySet().iterator();
while (iterator.hasNext()) {
String headerName = iterator.next().toString();
httpPut.addHeader(headerName, headers.get(headerName));
}
}
httpPut.addHeader("Content-Type", "application/json");
if (params != null) {
StringEntity stringEntity = new StringEntity(params.toJSONString());
httpPut.setEntity(stringEntity);
}
// 从响应模型中获得具体的实体
HttpEntity entity = httpClient.execute(httpPut).getEntity();
String response = EntityUtils.toString(entity);
httpClient.close();
return response;
}
public static class HttpDeleteWithBody extends HttpEntityEnclosingRequestBase {
public static final String METHOD_NAME = "DELETE";
@Override
public String getMethod() {
return METHOD_NAME;
}
public HttpDeleteWithBody(final String uri) {
super();
setURI(URI.create(uri));
}
public HttpDeleteWithBody(final URI uri) {
super();
setURI(uri);
}
public HttpDeleteWithBody() {
super();
}
}
}
3、主要实现类EditConfiguration.class
package com.nacos.util;
import com.alibaba.fastjson.JSONObject;
import org.apache.http.client.utils.URIBuilder;
import org.yaml.snakeyaml.DumperOptions;
import org.yaml.snakeyaml.Yaml;
import java.io.*;
import java.net.URI;
import java.net.URISyntaxException;
import java.util.HashMap;
import java.util.Map;
/**
* @author: zhaoxu
* @description:
*/
public class EditConfiguration {
final static String headerAgent = "User-Agent";
final static String headerAgentArg = "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/84.0.4147.135 Safari/537.36";
/**
* nacos ip
*/
static String ip = "";
static String dataId = "";
static String group = "";
static String updateKey = "";
static String newString = "";
static String username = "";
static String password = "";
static String accessToken = "";
static String id = "";
static String md5 = "";
static String appName = "";
static String type = "";
static Map yamlConfig = new HashMap<String, String>();
public static void main(String[] args) throws IOException, URISyntaxException {
initData();
Login();
getYamlConfig();
Object valueByKey = getValueByKey(updateKey);
setYamlConfig(yamlConfig, updateKey, newString);
DumperOptions dumperOptions = new DumperOptions();
dumperOptions.setDefaultFlowStyle(DumperOptions.FlowStyle.BLOCK);
Yaml yaml = new Yaml(dumperOptions);
String dump = yaml.dump(yamlConfig);
publish(dump);
}
public static void Login() throws IOException {
String post = HttpClientUtil.post(null, "http://" + ip + ":18001/nacos/v1/auth/users/login?username=" + username + "&password=" + password, null);
accessToken = JSONObject.parseObject(post).get("accessToken").toString();
}
public static void getYamlConfig() throws IOException {
String response = HttpClientUtil.get(null, "http://" + ip + ":18001/nacos/v1/cs/configs?dataId=" + dataId + "&group=" + group + "&namespaceId=&tenant=&show=all&accessToken=" + accessToken, null);
String content = JSONObject.parseObject(response).get("content").toString();
id = JSONObject.parseObject(response).get("id").toString();
md5 = JSONObject.parseObject(response).get("md5").toString();
try {
Yaml yaml = new Yaml();
if (content != null) {
//可以将值转换为Map
yamlConfig = yaml.load(new ByteArrayInputStream(content.getBytes()));
}
} catch (Exception e) {
e.printStackTrace();
}
}
public static Map<String, Object> setYamlConfig(Map<String, Object> map, String key, Object value) {
String[] keys = key.split("\\.");
int len = keys.length;
Map temp = map;
for (int i = 0; i < len - 1; i++) {
if (temp.containsKey(keys[i])) {
temp = (Map) temp.get(keys[i]);
} else {
return null;
}
if (i == len - 2) {
temp.put(keys[i + 1], value);
}
}
for (int j = 0; j < len - 1; j++) {
if (j == len - 1) {
map.put(keys[j], temp);
}
}
return map;
}
public static Object getValueByKey(String key) {
String separator = ".";
String[] separatorKeys = null;
if (key.contains(separator)) {
separatorKeys = key.split("\\.");
} else {
return yamlConfig.get(key);
}
Map<String, Map<String, Object>> finalValue = new HashMap();
for (int i = 0; i < separatorKeys.length - 1; i++) {
if (i == 0) {
finalValue = (Map) yamlConfig.get(separatorKeys[i]);
continue;
}
if (finalValue == null) {
break;
}
finalValue = (Map) finalValue.get(separatorKeys[i]);
}
return finalValue.get(separatorKeys[separatorKeys.length - 1]);
}
public static void initData() throws IOException {
String fileData = readFile("InitData.iml").toString();
try {
ip = fileData.split("ip=")[1].split(";")[0];
dataId = fileData.split("dataId=")[1].split(";")[0];
group = fileData.split("group=")[1].split(";")[0];
username = fileData.split("username=")[1].split(";")[0];
password = fileData.split("password=")[1].split(";")[0];
type = fileData.split("type=")[1].split(";")[0];
type = fileData.split("type=")[1].split(";")[0];
updateKey = fileData.split("updateKey=")[1].split(";")[0];
newString = fileData.split("newString=")[1].split(";")[0];
} catch (Exception e) {
System.out.println("参数错误,每个参数后面需要加分号");
}
}
public static void publish(String dump) throws IOException, URISyntaxException {
URI uri = new URIBuilder("http://" + ip + ":18001/nacos/v1/cs/configs?dataId=" + dataId + "&group=" + group + "&id=" + id + "" +
"&md5=" + md5 + "appName=" + appName + "&accessToken=" + accessToken).setParameter("content", dump).setParameter("type", type).build();
HttpClientUtil.postMap(null, uri, null);
}
/**
* 按行读取全部文件数据
*
* @param strFile
*/
public static StringBuffer readFile(String strFile) throws IOException {
StringBuffer strSb = new StringBuffer();
InputStreamReader inStrR = new InputStreamReader(new FileInputStream(strFile), "UTF-8");
// character streams
BufferedReader br = new BufferedReader(inStrR);
String line = br.readLine();
while (line != null) {
strSb.append(line).append("\r\n");
line = br.readLine();
}
return strSb;
}
}
4、配置文件,需要在项目根目录下创建InitData.iml文件,作为配置文件
ip=192.168.90.230;
username=nacos;
password=nacos;
dataId=are-oms-tankInfo-zx.yaml;
group=oms;
type=yaml;
updateKey=spring.datasource.url;
newString=zxzxzxzxzxzxzxzxzxzxz;