Javaでnacosにログインし、設定を変更して公開する。
2022-02-19 16:50:31
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>
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 request, params can be null, headers can be 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();
// Create get request
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");
// Get the specific entity from the response model
HttpEntity entity = httpClient.execute(httpGet).getEntity();
String response = EntityUtils.toString(entity);
httpClient.close();
return response;
}
/**
* post request, params can be null, headers can be 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();
// Create a post request
HttpPost http
httpPost.addHeader(headerName, headers.get(headerName));
}
}
httpPost.addHeader("Content-Type", "application/json");
if (params ! = null) {
StringEntity stringEntity = new StringEntity(params.toJSONString());
httpPost.setEntity(stringEntity);
}
// Get the specific entity from the response model
HttpEntity entity = httpClient.execute(httpPost).getEntity();
String response = EntityUtils.toString(entity);
httpClient.close();
return response;
}
/**
* post request, params can be null, headers can be 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();
// create post request
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);
}
// Get the specific entity from the response model
HttpEntity entity = httpClient.execute(httpPost).getEntity();
String response = EntityUtils.toString(entity);
httpClient.close();
return response;
}
/**
* delete,params can be null,headers can be 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();
// create delete request, HttpDeleteWithBody for the internal class, class below
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);
}
// Get the specific entity from the response model
HttpEntity entity = httpClient.execute(httpDelete).getEntity();
String response = EntityUtils.toString(entity);
httpClient.close();
return response;
}
/**
* put,params can be null,headers can be 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();
// Create put request
HttpPut httpPut = new HttpPut(url);
if (headers ! = null) {
Iterator iterator = headers.keySet().iterator();
while (iterator.hasNext()) {
String headerName = iterator.next().toString();
httpPut.a
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 + "& amp;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=&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) {
// you can convert the value to 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("Parameter error, each parameter needs to be followed by a semicolon");
}
}
public static void publish(String dump) throws IOException, URISyntaxException {
URI uri = new URIBuilder("http://" + ip + ":18001/nacos/v1/cs/configs?dataId=" + dataId + "&group=" + group + " quot;&id=" + id + "" +
"&md5=" + md5 + "appName=" + appName + "&accessToken=" + accessToken).setParameter("content" , dump).setParameter("type", type).build();
HttpClientUtil.postMap(null, uri, null);
}
/**
* Read all file data by line
*
* @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;
}
}
ip=192.168.90.230;
username=nacos;
password=nacos;
dataId=are-oms-tankInfo-zx.yaml;
group=oms;
type=yaml;
updateKey=spring.datasource.url;
newString=zxzxzxzxzxzxzxzxzxzxzz;
2.
HttpClientUtil.class
ツールクラス
EditConfiguration.class
3. 主な実装クラス
InitData.iml
InitData.iml
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=zxzxzxzxzxzxzxzxzxzxzz;
関連
-
未定義のプロパティ 'init' を読み取ることができません。
-
can't find '__main__' module in "問題の詳細!
-
[エラー] '{' トークンの前に期待される式
-
[Android Studioのエラー] Emulator: HAXの初期化に失敗しました: 無効な引数です。
-
python prompts ImportError: Image という名前のモジュールがありません。
-
python problem: SyntaxError: 1つのステートメントをコンパイルする際に複数のステートメントが見つかる
-
Pythonラーニングノートです。TypeError: cannot use a string pattern on a bytes-like object とその解決法
-
numpy.concatenate merge matrix エラー ValueError: すべての入力配列は同じ次元数でなければなりません。
-
eclipseに「An error has occurred,See the error log for more details.java.lang.NullPointerException」と表示される。
-
エラーの解決策 xmlのこの行に複数のアノテーションが見つかりました。
最新
-
nginxです。[emerg] 0.0.0.0:80 への bind() に失敗しました (98: アドレスは既に使用中です)
-
htmlページでギリシャ文字を使うには
-
ピュアhtml+cssでの要素読み込み効果
-
純粋なhtml + cssで五輪を実現するサンプルコード
-
ナビゲーションバー・ドロップダウンメニューのHTML+CSSサンプルコード
-
タイピング効果を実現するピュアhtml+css
-
htmlの選択ボックスのプレースホルダー作成に関する質問
-
html css3 伸縮しない 画像表示効果
-
トップナビゲーションバーメニュー作成用HTML+CSS
-
html+css 実装 サイバーパンク風ボタン
おすすめ
-
スキャナは、入力を待たずにエラーを報告します java.util.NoSuchElementException: 行が見つかりません
-
undefineddouble' の前にある期待される一次式を解決します。
-
Pythonではbreak文とcontinue文はifとしか使えないのでしょうか?
-
plot.new() のエラー : Rstudio での図形の余白が大きすぎる解決法
-
python reports an error: 'list' object has no attribute 'shape'
-
を作ってください。*** ターゲットが指定されておらず、makefileも見つかりませんでした。
-
ResultSet が閉じた後の操作は許可されない ResultSet 閉鎖例外
-
ValueErrorの解決策です。閉じたファイルへの I/O 操作
-
Python で 'str' と 'int' のインスタンス間でエラー '>=' がサポートされていない
-
win7 to win10 api-ms-win-core-libraryloader-l1-1-1.dll is missing.