千家信息网

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

发表于:2026-10-31 作者:千家信息网编辑
千家信息网最后更新 2026年10月31日,这篇文章主要介绍"nacos client中ServerHttpAgent的原理和使用方法",在日常操作中,相信很多人在nacos client中ServerHttpAgent的原理和使用方法问题上存
千家信息网最后更新 2026年10月31日nacos client中ServerHttpAgent的原理和使用方法

这篇文章主要介绍"nacos client中ServerHttpAgent的原理和使用方法",在日常操作中,相信很多人在nacos client中ServerHttpAgent的原理和使用方法问题上存在疑惑,小编查阅了各式资料,整理出简单好用的操作方法,希望对大家解答"nacos client中ServerHttpAgent的原理和使用方法"的疑惑有所帮助!接下来,请跟着小编一起来学习吧!

序

本文主要研究一下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 headers, List 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 headers, List 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 headers, List 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 headers, List 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 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 headers, List 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 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

到此,关于"nacos client中ServerHttpAgent的原理和使用方法"的学习就结束了,希望能够解决大家的疑惑。理论与实践的搭配能更好的帮助大家学习,快去试试吧!若想继续学习更多相关知识,请继续关注网站,小编会继续努力为大家带来更多实用的文章!

方法 循环 使用方法 原理 学习 相同 接口 时间 更多 条件 结构 帮助 实用 接下来 小结 开头 循环体 文章 日志 理论 数据库的安全要保护哪些东西 数据库安全各自的含义是什么 生产安全数据库录入 数据库的安全性及管理 数据库安全策略包含哪些 海淀数据库安全审计系统 建立农村房屋安全信息数据库 易用的数据库客户端支持安全管理 连接数据库失败ssl安全错误 数据库的锁怎样保障安全 互联网科技公司经营范围 江苏根荣互联网科技 科技信息互联网 云电互联网科技 互联网科技logo设计 互联网科技咨询 互联网 科技服务平台 滨湖区互联网智能科技产品供应 太原新华互联网科技学校怎么样 科技互联网的估值 互联网大会黑科技排名 互联网和黑科技的看法 厦门千工互联网科技有限公司 西安小鹰速贷互联网科技有限公司 互联网科技大赛获奖感言 世界互联网领先科技成果获奖 互联网领先科技宣传片 互联网科技融合创新 陕西云淼互联网科技公司 平安好医生打造互联网科技医疗 时间互联网络科技 千方科技属于互联网企业吗 成都互联网科技公司工作好不好 互联网科技公司营业执照怎么办理 合肥互联网科技公司公章图片 本届互联网大会上的黑科技 湖北辰鑫科技互联网 北京天晋互联网科技有限公司 深圳互联网科技园地址 科技互联网专业工作会议发言稿
0