文档章节

聊聊nacos client的ServerHttpAgent

go4it
 go4it
发布于 10/16 22:48
字数 846
阅读 16
收藏 0

本文主要研究一下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          相对于web应用根,以/开头
     * @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实现了HttpAgent接口,其httpGet、httpPost、httpDelete方法的结构大体相同,都是以do while做循环,循环条件为距离开始执行时间不超过readTimeoutMs
  • 循环开始之前会通过serverListMgr.getCurrentServerAddr()方法获取currentServerAddr,循环体内则通过HttpSimpleClient的相应方法执行请求,如果返回的HTTP Code为HTTP_INTERNAL_ERROR、HTTP_BAD_GATEWAY、HTTP_UNAVAILABLE则打印error日志,否则执行serverListMgr.updateCurrentServerAddr(currentServerAddr),然后返回
  • 如果出现异常或者没有提前返回,则判断serverListMgr.getIterator().hasNext(),如果为true则使用serverListMgr.getIterator().next()更新currentServerAddr,为false则递减maxRetry,然后执行serverListMgr.refreshCurrentServerAddr()

小结

ServerHttpAgent实现了HttpAgent接口,其httpGet、httpPost、httpDelete方法的结构大体相同,都是以do while做循环,循环条件为距离开始执行时间不超过readTimeoutMs

doc

© 著作权归作者所有

go4it
粉丝 88
博文 1158
码字总数 1089254
作品 0
深圳
私信 提问
聊聊nacos client的MetricsMonitor

序 本文主要研究一下nacos client的MetricsMonitor MetricsMonitor nacos-1.1.3/client/src/main/java/com/alibaba/nacos/client/monitor/MetricsMonitor.java MetricsMonitor内置了nacosMo......

go4it
09/03
32
0
聊聊nacos config的RequestLogAspect

序 本文主要研究一下nacos config的RequestLogAspect RequestLogAspect nacos-1.1.3/config/src/main/java/com/alibaba/nacos/config/server/aspect/RequestLogAspect.java RequestLogAspec......

go4it
09/05
20
0
聊聊nacos的ServerStatusManager

序 本文主要研究一下nacos的ServerStatusManager ServerStatusManager nacos-1.1.3/naming/src/main/java/com/alibaba/nacos/naming/cluster/ServerStatusManager.java ServerStatusManager的......

go4it
09/04
36
0
聊聊nacos的DistroFilter

序 本文主要研究一下nacos的DistroFilter CanDistro nacos-1.1.3/naming/src/main/java/com/alibaba/nacos/naming/web/CanDistro.java CanDistro用于标识一个方法需要判断是否应该根据distr......

go4it
09/11
20
0
Nacos: Namespace 和 Endpoint 在生产环境下的最佳实践

随着使用 Nacos 的企业越来越多,遇到的最频繁的两个问题就是:如何在我的生产环境正确的来使用 namespace 以及 endpoint。这篇文章主要就是针对这两个问题来聊聊使用 nacos 过程中关于这两个...

中间件小哥
05/27
0
0

没有更多内容

加载失败,请刷新页面

加载更多

Mysql备份还有这么多套路,还不了解下?

逻辑备份和物理备份 逻辑备份 逻辑备份用于备份数据库的结构(CREAET DATABASE、CREATE TABLE)和数据(INSERT),这种备份类型适合数据量小、跨SQL服务器、需要修改数据等场景。如mysqldump...

架构文摘
15分钟前
4
0
吊打面试官——秒杀系统设计

首先设计一个系统之前,我们需要先确认我们的业务场景是怎么样子的,我就带着大家一起假设一个场景好吧。 场景 我们现在要卖100件下面这个婴儿纸尿裤,然后我们根据以往这样秒杀活动的数据经...

java后端开发
21分钟前
3
0
高频电子电路电磁兼容的设计要点

电磁兼容的问题常发生于高频状态下,个别问题(电压跌落与瞬时中断等)除外。高频思维,总而言之,就是器件的特性、电路的特性,在高频情况下和常规中低频 状态下是不一样的,如果仍然按照普...

demyar
22分钟前
2
0
JDK 12 JVM 垃圾回收器 Shenandoah GC 的实践案例

https://www.infoq.cn/article/L4LU1J0VxXtA6ASeGYbV

perofu
32分钟前
3
0
Linux下的计划任务--cron

linux任务计划cron介绍 大部分系统管理工作都是通过定期自动执行某个脚本来完成的,Linux的cron就是用来定期执行脚本的。 Linux任务计划功能的操作都是通过crontab命令来完成的,常用的选项有...

爱米修啊
33分钟前
4
0

没有更多内容

加载失败,请刷新页面

加载更多

返回顶部
顶部