sequence

This article mainly studies the ServerHttpAgent of NACOS Client

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
     * @returnNothing. * @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 * @paramreadTimeoutMs 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();
}
Copy the code
  • HttpAgent defines the start, httpGet, httpPost, httpDelete, getName, getNamespace, getTenant, and getEncode methods

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 Relative to the Web application root, starting with /* @param headers * @param paramValues * @param encoding * @paramreadTimeoutMs
     * @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); } / /... }Copy the code
  • ServerHttpAgent implements the HttpAgent interface. The structure of httpGet, httpPost and httpDelete methods are roughly the same. They are all done in a do while loop, and the loop condition is that the execution time does not exceed readTimeoutMs
  • . Before the start of cycle through serverListMgr getCurrentServerAddr () method to obtain currentServerAddr, circulating in the body by HttpSimpleClient corresponding method to execute the request, If the returned HTTP Code is HTTP_INTERNAL_ERROR, HTTP_BAD_GATEWAY, or HTTP_UNAVAILABLE, an error log is displayed. Otherwise do serverListMgr. UpdateCurrentServerAddr (currentServerAddr), and then return
  • If abnormal, or does not return early, judge serverListMgr. GetIterator () hasNext (), if use the serverListMgr to true getIterator (). The next update currentServerAddr (), To false maxRetry is decreasing, and then execute serverListMgr. RefreshCurrentServerAddr ()

summary

ServerHttpAgent implements the HttpAgent interface. The structure of httpGet, httpPost and httpDelete methods are roughly the same. They are all done in a do while loop, and the loop condition is that the execution time does not exceed readTimeoutMs

doc

  • ServerHttpAgent