[NACOS HTTP-GET] The maximum number of tolerable server reconnection errors has been reached
错误的意思是:已达到可容忍的服务器重连接错误的最大数目。
有两个解决思路:一个将这个值设置的更大;然后是排查自己连接服务哪儿出了问题。
先说在哪儿设置这个值:在拉取nacos服务的注解配置中,添加一个属性maxRetry,这个值源码中默认给的是3,可以将其设置的更大一些。
@Configuration
@EnableNacosConfig(globalProperties = @NacosProperties(serverAddr = "127.0.0.1:8848", namespace = "xxxxxxxxxxxxxxxxxx", maxRetry = "10"))
@NacosPropertySources({ @NacosPropertySource(dataId = "url.properties", groupId = "test_group", autoRefreshed = true), @NacosPropertySource(dataId = "db.properties", groupId = "test_group", autoRefreshed = true), @NacosPropertySource(dataId = "xxl-job.properties", groupId = "test_group", autoRefreshed = true)
})
public class NacosConfiguration { }
nacos-clinent架包中,找到ServerHttpAgent类。
包的全路经:com.alibaba.nacos.client.config.http.ServerHttpAgent
可以看到设置错误的最大连接数目默认值为3,private int maxRetry = 3;
在方法httpGet中,如果出现异常或者没有提前返回,则判断serverListMgr.getIterator().hasNext(),如果为true则使用serverListMgr.getIterator().next()更新currentServerAddr,为false则递减maxRetry,maxRetry=0时则抛出异常[NACOS HTTP-GET] The maximum number of tolerable server reconnection errors has been reached
/*
* Copyright 1999-2018 Alibaba Group Holding Ltd.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
package com.alibaba.nacos.client.config.http; import com.alibaba.nacos.api.PropertyKeyConst;
import com.alibaba.nacos.api.common.Constants;
import com.alibaba.nacos.api.exception.NacosException;
import com.alibaba.nacos.client.config.impl.HttpSimpleClient;
import com.alibaba.nacos.client.config.impl.HttpSimpleClient.HttpResult;
import com.alibaba.nacos.client.config.impl.ServerListManager;
import com.alibaba.nacos.client.config.impl.SpasAdapter;
import com.alibaba.nacos.client.config.utils.IOUtils;
import com.alibaba.nacos.client.identify.STSConfig;
import com.alibaba.nacos.client.utils.TemplateUtils;
import com.alibaba.nacos.client.utils.JSONUtils;
import com.alibaba.nacos.client.utils.LogUtils;
import com.alibaba.nacos.client.utils.ParamUtil;
import com.alibaba.nacos.client.utils.StringUtils;
import com.fasterxml.jackson.annotation.JsonProperty;
import com.fasterxml.jackson.core.type.TypeReference;
import org.apache.commons.lang3.math.NumberUtils;
import org.slf4j.Logger;
import java.io.IOException;
import java.net.ConnectException;
import java.net.HttpURLConnection;
import java.net.SocketTimeoutException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Properties;
import java.util.concurrent.Callable; /**
* Server Agent
*
* @author water.lyl
*/
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);
} @Override
public HttpResult httpDelete(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.httpDelete(
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 httpDelete] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), ce.getMessage());
} catch (SocketTimeoutException stoe) {
LOGGER.error("[NACOS SocketTimeoutException httpDelete] currentServerAddr:{}, err : {}", serverListMgr.getCurrentServerAddr(), stoe.getMessage());
} catch (IOException ioe) {
LOGGER.error("[NACOS IOException httpDelete] currentServerAddr: " + serverListMgr.getCurrentServerAddr(), ioe);
throw ioe;
} if (serverListMgr.getIterator().hasNext()) {
currentServerAddr = serverListMgr.getIterator().next();
} else {
maxRetry --;
if (maxRetry < 0) {
throw new ConnectException("[NACOS HTTP-DELETE] 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");
} private String getUrl(String serverAddr, String relativePath) {
return serverAddr + "/" + serverListMgr.getContentPath() + relativePath;
} public static String getAppname() {
return ParamUtil.getAppName();
} public ServerHttpAgent(ServerListManager mgr) {
serverListMgr = mgr;
} public ServerHttpAgent(ServerListManager mgr, Properties properties) {
serverListMgr = mgr;
init(properties);
} public ServerHttpAgent(Properties properties) throws NacosException {
serverListMgr = new ServerListManager(properties);
init(properties);
} private void init(Properties properties) {
initEncode(properties);
initAkSk(properties);
initMaxRetry(properties);
} private void initEncode(Properties properties) {
encode = TemplateUtils.stringEmptyAndThenExecute(properties.getProperty(PropertyKeyConst.ENCODE), new Callable<String>() {
@Override
public String call() throws Exception {
return Constants.ENCODE;
}
});
} private void initAkSk(Properties properties) {
String ramRoleName = properties.getProperty(PropertyKeyConst.RAM_ROLE_NAME);
if (!StringUtils.isBlank(ramRoleName)) {
STSConfig.getInstance().setRamRoleName(ramRoleName);
} String ak = properties.getProperty(PropertyKeyConst.ACCESS_KEY);
if (StringUtils.isBlank(ak)) {
accessKey = SpasAdapter.getAk();
} else {
accessKey = ak;
} String sk = properties.getProperty(PropertyKeyConst.SECRET_KEY);
if (StringUtils.isBlank(sk)) {
secretKey = SpasAdapter.getSk();
} else {
secretKey = sk;
}
} private void initMaxRetry(Properties properties) {
maxRetry = NumberUtils.toInt(String.valueOf(properties.get(PropertyKeyConst.MAX_RETRY)), Constants.MAX_RETRY);
} @Override
public synchronized void start() throws NacosException {
serverListMgr.start();
} private List<String> getSpasHeaders(List<String> paramValues) throws IOException {
List<String> newHeaders = new ArrayList<String>();
// STS 临时凭证鉴权的优先级高于 AK/SK 鉴权
if (STSConfig.getInstance().isSTSOn()) {
STSCredential sTSCredential = getSTSCredential();
accessKey = sTSCredential.accessKeyId;
secretKey = sTSCredential.accessKeySecret;
newHeaders.add("Spas-SecurityToken");
newHeaders.add(sTSCredential.securityToken);
} if (StringUtils.isNotEmpty(accessKey) && StringUtils.isNotEmpty(secretKey)) {
newHeaders.add("Spas-AccessKey");
newHeaders.add(accessKey);
List<String> signHeaders = SpasAdapter.getSignHeaders(paramValues, secretKey);
if (signHeaders != null) {
newHeaders.addAll(signHeaders);
}
}
return newHeaders;
} private STSCredential getSTSCredential() throws IOException {
boolean cacheSecurityCredentials = STSConfig.getInstance().isCacheSecurityCredentials();
if (cacheSecurityCredentials && sTSCredential != null) {
long currentTime = System.currentTimeMillis();
long expirationTime = sTSCredential.expiration.getTime();
int timeToRefreshInMillisecond = STSConfig.getInstance().getTimeToRefreshInMillisecond();
if (expirationTime - currentTime > timeToRefreshInMillisecond) {
return sTSCredential;
}
}
String stsResponse = getSTSResponse();
STSCredential stsCredentialTmp = JSONUtils.deserializeObject(stsResponse,
new TypeReference<STSCredential>() {
});
sTSCredential = stsCredentialTmp;
LOGGER.info("[getSTSCredential] code:{}, accessKeyId:{}, lastUpdated:{}, expiration:{}", sTSCredential.getCode(),
sTSCredential.getAccessKeyId(), sTSCredential.getLastUpdated(), sTSCredential.getExpiration());
return sTSCredential;
} private static String getSTSResponse() throws IOException {
String securityCredentials = STSConfig.getInstance().getSecurityCredentials();
if (securityCredentials != null) {
return securityCredentials;
}
String securityCredentialsUrl = STSConfig.getInstance().getSecurityCredentialsUrl();
HttpURLConnection conn = null;
int respCode;
String response;
try {
conn = (HttpURLConnection) new URL(securityCredentialsUrl).openConnection();
conn.setRequestMethod("GET");
conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 100 ? ParamUtil.getConnectTimeout() : 100);
conn.setReadTimeout(1000);
conn.connect();
respCode = conn.getResponseCode();
if (HttpURLConnection.HTTP_OK == respCode) {
response = IOUtils.toString(conn.getInputStream(), Constants.ENCODE);
} else {
response = IOUtils.toString(conn.getErrorStream(), Constants.ENCODE);
}
} catch (IOException e) {
LOGGER.error("can not get security credentials", e);
throw e;
} finally {
if (null != conn) {
conn.disconnect();
}
}
if (HttpURLConnection.HTTP_OK == respCode) {
return response;
}
LOGGER.error("can not get security credentials, securityCredentialsUrl: {}, responseCode: {}, response: {}",
securityCredentialsUrl, respCode, response);
throw new IOException(
"can not get security credentials, responseCode: " + respCode + ", response: " + response);
} @Override
public String getName() {
return serverListMgr.getName();
} @Override
public String getNamespace() {
return serverListMgr.getNamespace();
} @Override
public String getTenant() {
return serverListMgr.getTenant();
} @Override
public String getEncode() {
return encode;
} @SuppressWarnings("PMD.ClassNamingShouldBeCamelRule")
private static class STSCredential {
@JsonProperty(value = "AccessKeyId")
private String accessKeyId;
@JsonProperty(value = "AccessKeySecret")
private String accessKeySecret;
@JsonProperty(value = "Expiration")
private Date expiration;
@JsonProperty(value = "SecurityToken")
private String securityToken;
@JsonProperty(value = "LastUpdated")
private Date lastUpdated;
@JsonProperty(value = "Code")
private String code; public String getAccessKeyId() {
return accessKeyId;
} public Date getExpiration() {
return expiration;
} public Date getLastUpdated() {
return lastUpdated;
} public String getCode() {
return code;
} @Override
public String toString() {
return "STSCredential{" +
"accessKeyId='" + accessKeyId + '\'' +
", accessKeySecret='" + accessKeySecret + '\'' +
", expiration=" + expiration +
", securityToken='" + securityToken + '\'' +
", lastUpdated=" + lastUpdated +
", code='" + code + '\'' +
'}';
}
} private String accessKey;
private String secretKey;
private String encode;
private int maxRetry = 3;
private volatile STSCredential sTSCredential;
final ServerListManager serverListMgr; }
[NACOS HTTP-GET] The maximum number of tolerable server reconnection errors has been reached的更多相关文章
- 执行tsung时报"Maximum number of concurrent users in a single VM reached
原创作品,允许转载,转载时请务必以超链接形式标明文章 原始出处 .作者信息和本声明.否则将追究法律责任.http://ovcer.blog.51cto.com/1145188/1581326 [roo ...
- iOS---The maximum number of apps for free development profiles has been reached.
真机调试免费App ID出现的问题The maximum number of apps for free development profiles has been reached.免费应用程序调试最 ...
- [LeetCode] Third Maximum Number 第三大的数
Given a non-empty array of integers, return the third maximum number in this array. If it does not e ...
- [LeetCode] Create Maximum Number 创建最大数
Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum numb ...
- LeetCode 414 Third Maximum Number
Problem: Given a non-empty array of integers, return the third maximum number in this array. If it d ...
- Failed to connect to database. Maximum number of conections to instance exceeded
我们大体都知道ArcSDE的连接数有 48 的限制,很多人也知道这个参数可以修改,并且每种操作系统能支持的最大连接数是不同的. 如果应用报错:超出系统最大连接数 该如何处理? 两种解决办法: 第一,首 ...
- POJ2699 The Maximum Number of Strong Kings
Time Limit: 1000MS Memory Limit: 65536K Total Submissions: 2102 Accepted: 975 Description A tour ...
- [LintCode] Create Maximum Number 创建最大数
Given two arrays of length m and n with digits 0-9 representing two numbers. Create the maximum numb ...
- tomcat 大并发报错 Maximum number of threads (200) created for connector with address null and port 8080
1.INFO: Maximum number of threads (200) created for connector with address null and port 8091 说明:最大线 ...
随机推荐
- CF741D Arpa’s letter-marked tree and Mehrdad’s Dokhtar-kosh paths——dsu on tree
题目描述 一棵根为1 的树,每条边上有一个字符(a-v共22种). 一条简单路径被称为Dokhtar-kosh当且仅当路径上的字符经过重新排序后可以变成一个回文串. 求每个子树中最长的Dokhtar- ...
- [转载]2.3 UiPath循环活动For Each的介绍和使用
一.For Each的介绍 For Each:循环迭代一个列表.数组.或其他类型的集合, 可以遍历并分别处理每条信息 二.For Each在UiPath中的使用 1.打开设计器,在设计库中新建一个Fl ...
- css3关于body的默认滑动机制
css关于body的默认滑动机制 大家都知道 body里面只要高度超出了原来的高度就可以滚动要取消这个机制 只能设置height:100% overflow:hidden就能取消了
- javascript获取上传图片的大小
javascript获取上传图片的大小 <pre><input id="file" type="file"> <input id= ...
- Hadoop4-HDFS分布式文件系统原理
一.简介 1.分布式文件系统钢结构 分布式文件系统由计算机集群中的多个节点构成,这些节点分为两类: 主节点(MasterNode)或者名称节点(NameNode) 从节点(Slave Node)或者数 ...
- [ PyQt入门教程 ] PyQt5中数据表格控件QTableWidget使用方法
如果你想让你开发的PyQt5工具展示的数据显得整齐.美观.好看,显得符合你的气质,可以考虑使用QTableWidget控件.之前一直使用的是textBrowser文本框控件,数据展示还是不太美观.其中 ...
- 数据分析之路 第一篇 numpy
第一篇 numpy 1.N维数组对象 :ndarray在Python中既然有了列表类型,为啥还要整个数组对象(类型)?那是因为:1.数组对象可以除去元素间运算所需要的循环,使得一维向量更像单个数据2. ...
- [LC]141题 Intersection of Two Linked Lists (相交链表)(链表)
①中文题目 编写一个程序,找到两个单链表相交的起始节点. 如下面的两个链表: 在节点 c1 开始相交. 注意: 如果两个链表没有交点,返回 null.在返回结果后,两个链表仍须保持原有的结构.可假定整 ...
- nyoj 70-阶乘因式分解(二)(数学)
70-阶乘因式分解(二) 内存限制:64MB 时间限制:3000ms 特判: No 通过数:7 提交数:7 难度:3 题目描述: 给定两个数n,m,其中m是一个素数. 将n(0<=n<=2 ...
- linux文件时间
Linux 查看文件修改时间(精确到秒)(简单) ls --full-time 查看文件时间戳命令:stat test.txt linux 下查看文件修改时间 等(详细) 查看文件时间戳命令:stat ...