溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

nacos client中ServerHttpAgent的原理和使用方法

發(fā)布時(shí)間:2021-06-28 16:52:27 來(lái)源:億速云 閱讀:805 作者:chen 欄目:大數(shù)據(jù)

這篇文章主要介紹“nacos client中ServerHttpAgent的原理和使用方法”,在日常操作中,相信很多人在nacos client中ServerHttpAgent的原理和使用方法問題上存在疑惑,小編查閱了各式資料,整理出簡(jiǎn)單好用的操作方法,希望對(duì)大家解答”nacos client中ServerHttpAgent的原理和使用方法”的疑惑有所幫助!接下來(lái),請(qǐng)跟著小編一起來(lái)學(xué)習(xí)吧!

本文主要研究一下nacos client的ServerHttpAgent

HttpAgent

nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/config/http/HttpAgent.java

public interface HttpAgent {
    /**
     * start to get nacos ip list
     * @return Nothing.
     * @throws NacosException on get ip list error.
     */
    void start() throws NacosException;

    /**
     * invoke http get method
     * @param path http path
     * @param headers http headers
     * @param paramValues http paramValues http
     * @param encoding http encode
     * @param readTimeoutMs http timeout
     * @return HttpResult http response
     * @throws IOException If an input or output exception occurred
     */

    HttpResult httpGet(String path, List<String> headers, List<String> paramValues, String encoding, long readTimeoutMs) throws IOException;

    /**
     * invoke http post method
     * @param path http path
     * @param headers http headers
     * @param paramValues http paramValues http
     * @param encoding http encode
     * @param readTimeoutMs http timeout
     * @return HttpResult http response
     * @throws IOException If an input or output exception occurred
     */
    HttpResult httpPost(String path, List<String> headers, List<String> paramValues, String encoding, long readTimeoutMs) throws IOException;

    /**
     * invoke http delete method
     * @param path http path
     * @param headers http headers
     * @param paramValues http paramValues http
     * @param encoding http encode
     * @param readTimeoutMs http timeout
     * @return HttpResult http response
     * @throws IOException If an input or output exception occurred
     */
    HttpResult httpDelete(String path, List<String> headers, List<String> paramValues, String encoding, long readTimeoutMs) throws IOException;

    /**
     * get name
     * @return String
     */
    String getName();

    /**
     * get namespace
     * @return String
     */
    String getNamespace();

    /**
     * get tenant
     * @return String
     */
    String getTenant();

    /**
     * get encode
     * @return String
     */
    String getEncode();
}
  • HttpAgent定義了start、httpGet、httpPost、httpDelete、getName、getNamespace、getTenant、getEncode方法

ServerHttpAgent

nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/config/http/ServerHttpAgent.java

public class ServerHttpAgent implements HttpAgent {

    private static final Logger LOGGER = LogUtils.logger(ServerHttpAgent.class);

    /**
     * @param path          相對(duì)于web應(yīng)用根,以/開頭
     * @param headers
     * @param paramValues
     * @param encoding
     * @param readTimeoutMs
     * @return
     * @throws IOException
     */
    @Override
    public HttpResult httpGet(String path, List<String> headers, List<String> paramValues, String encoding,
                              long readTimeoutMs) throws IOException {
        final long endTime = System.currentTimeMillis() + readTimeoutMs;
        final boolean isSSL = false;

        String currentServerAddr = serverListMgr.getCurrentServerAddr();
        int maxRetry = this.maxRetry;

        do {
            try {
                List<String> newHeaders = getSpasHeaders(paramValues);
                if (headers != null) {
                    newHeaders.addAll(headers);
                }
                HttpResult result = HttpSimpleClient.httpGet(
                    getUrl(currentServerAddr, path), newHeaders, paramValues, encoding,
                    readTimeoutMs, isSSL);
                if (result.code == HttpURLConnection.HTTP_INTERNAL_ERROR
                    || result.code == HttpURLConnection.HTTP_BAD_GATEWAY
                    || result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
                    LOGGER.error("[NACOS ConnectException] currentServerAddr: {}, httpCode: {}",
                        serverListMgr.getCurrentServerAddr(), result.code);
                } else {
                    // Update the currently available server addr
                    serverListMgr.updateCurrentServerAddr(currentServerAddr);
                    return result;
                }
            } catch (ConnectException ce) {
                LOGGER.error("[NACOS ConnectException httpGet] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), ce.getMessage());
            } catch (SocketTimeoutException stoe) {
                LOGGER.error("[NACOS SocketTimeoutException httpGet] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), stoe.getMessage());
            } catch (IOException ioe) {
                LOGGER.error("[NACOS IOException httpGet] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ioe);
                throw ioe;
            }

            if (serverListMgr.getIterator().hasNext()) {
                currentServerAddr = serverListMgr.getIterator().next();
            } else {
                maxRetry --;
                if (maxRetry < 0) {
                    throw new ConnectException("[NACOS HTTP-GET] The maximum number of tolerable server reconnection errors has been reached");
                }
                serverListMgr.refreshCurrentServerAddr();
            }

        } while (System.currentTimeMillis() <= endTime);

        LOGGER.error("no available server");
        throw new ConnectException("no available server");
    }

    @Override
    public HttpResult httpPost(String path, List<String> headers, List<String> paramValues, String encoding,
                               long readTimeoutMs) throws IOException {
        final long endTime = System.currentTimeMillis() + readTimeoutMs;
        boolean isSSL = false;

        String currentServerAddr = serverListMgr.getCurrentServerAddr();
        int maxRetry = this.maxRetry;

        do {

            try {
                List<String> newHeaders = getSpasHeaders(paramValues);
                if (headers != null) {
                    newHeaders.addAll(headers);
                }

                HttpResult result = HttpSimpleClient.httpPost(
                    getUrl(currentServerAddr, path), newHeaders, paramValues, encoding,
                    readTimeoutMs, isSSL);
                if (result.code == HttpURLConnection.HTTP_INTERNAL_ERROR
                    || result.code == HttpURLConnection.HTTP_BAD_GATEWAY
                    || result.code == HttpURLConnection.HTTP_UNAVAILABLE) {
                    LOGGER.error("[NACOS ConnectException] currentServerAddr: {}, httpCode: {}",
                        currentServerAddr, result.code);
                } else {
                    // Update the currently available server addr
                    serverListMgr.updateCurrentServerAddr(currentServerAddr);
                    return result;
                }
            } catch (ConnectException ce) {
                LOGGER.error("[NACOS ConnectException httpPost] currentServerAddr: {}, err : {}", currentServerAddr, ce.getMessage());
            } catch (SocketTimeoutException stoe) {
                LOGGER.error("[NACOS SocketTimeoutException httpPost] currentServerAddr: {}, err : {}", currentServerAddr, stoe.getMessage());
            } catch (IOException ioe) {
                LOGGER.error("[NACOS IOException httpPost] currentServerAddr: " + currentServerAddr, ioe);
                throw ioe;
            }

            if (serverListMgr.getIterator().hasNext()) {
                currentServerAddr = serverListMgr.getIterator().next();
            } else {
                maxRetry --;
                if (maxRetry < 0) {
                    throw new ConnectException("[NACOS HTTP-POST] The maximum number of tolerable server reconnection errors has been reached");
                }
                serverListMgr.refreshCurrentServerAddr();
            }

        } while (System.currentTimeMillis() <= endTime);

        LOGGER.error("no available server, currentServerAddr : {}", currentServerAddr);
        throw new ConnectException("no available server, currentServerAddr : " + currentServerAddr);
    }

    //......
}
  • ServerHttpAgent實(shí)現(xiàn)了HttpAgent接口,其httpGet、httpPost、httpDelete方法的結(jié)構(gòu)大體相同,都是以do while做循環(huán),循環(huán)條件為距離開始執(zhí)行時(shí)間不超過(guò)readTimeoutMs

  • 循環(huán)開始之前會(huì)通過(guò)serverListMgr.getCurrentServerAddr()方法獲取currentServerAddr,循環(huán)體內(nèi)則通過(guò)HttpSimpleClient的相應(yīng)方法執(zhí)行請(qǐng)求,如果返回的HTTP Code為HTTP_INTERNAL_ERROR、HTTP_BAD_GATEWAY、HTTP_UNAVAILABLE則打印error日志,否則執(zhí)行serverListMgr.updateCurrentServerAddr(currentServerAddr),然后返回

  • 如果出現(xiàn)異?;蛘邲]有提前返回,則判斷serverListMgr.getIterator().hasNext(),如果為true則使用serverListMgr.getIterator().next()更新currentServerAddr,為false則遞減maxRetry,然后執(zhí)行serverListMgr.refreshCurrentServerAddr()

小結(jié)

ServerHttpAgent實(shí)現(xiàn)了HttpAgent接口,其httpGet、httpPost、httpDelete方法的結(jié)構(gòu)大體相同,都是以do while做循環(huán),循環(huán)條件為距離開始執(zhí)行時(shí)間不超過(guò)readTimeoutMs

到此,關(guān)于“nacos client中ServerHttpAgent的原理和使用方法”的學(xué)習(xí)就結(jié)束了,希望能夠解決大家的疑惑。理論與實(shí)踐的搭配能更好的幫助大家學(xué)習(xí),快去試試吧!若想繼續(xù)學(xué)習(xí)更多相關(guān)知識(shí),請(qǐng)繼續(xù)關(guān)注億速云網(wǎng)站,小編會(huì)繼續(xù)努力為大家?guī)?lái)更多實(shí)用的文章!

向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI