1. ホーム

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

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;