From 796849b17d88ab93ccdcb091531d4d9c9a535db7 Mon Sep 17 00:00:00 2001 From: "mai.jh" Date: Thu, 5 Nov 2020 09:10:30 +0800 Subject: [PATCH] refactor: delete the old http client code marked as @Deprecated (#4122) --- .../client/config/impl/HttpSimpleClient.java | 305 ------------------ .../nacos/client/naming/net/HttpClient.java | 248 -------------- .../nacos/common/http/BaseHttpClient.java | 124 ------- .../nacos/common/http/HttpClientManager.java | 88 ----- .../nacos/common/http/NAsyncHttpClient.java | 95 ------ .../nacos/common/http/NHttpClient.java | 31 -- .../nacos/common/http/NSyncHttpClient.java | 98 ------ .../common/http/NacosAsyncHttpClient.java | 83 ----- .../common/http/NacosSyncHttpClient.java | 83 ----- .../StartingSpringApplicationRunListener.java | 3 - .../controller/NacosClusterController.java | 8 +- 11 files changed, 4 insertions(+), 1162 deletions(-) delete mode 100644 client/src/main/java/com/alibaba/nacos/client/config/impl/HttpSimpleClient.java delete mode 100644 client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java delete mode 100644 common/src/main/java/com/alibaba/nacos/common/http/BaseHttpClient.java delete mode 100644 common/src/main/java/com/alibaba/nacos/common/http/HttpClientManager.java delete mode 100644 common/src/main/java/com/alibaba/nacos/common/http/NAsyncHttpClient.java delete mode 100644 common/src/main/java/com/alibaba/nacos/common/http/NHttpClient.java delete mode 100644 common/src/main/java/com/alibaba/nacos/common/http/NSyncHttpClient.java delete mode 100644 common/src/main/java/com/alibaba/nacos/common/http/NacosAsyncHttpClient.java delete mode 100644 common/src/main/java/com/alibaba/nacos/common/http/NacosSyncHttpClient.java diff --git a/client/src/main/java/com/alibaba/nacos/client/config/impl/HttpSimpleClient.java b/client/src/main/java/com/alibaba/nacos/client/config/impl/HttpSimpleClient.java deleted file mode 100644 index 67187378c07..00000000000 --- a/client/src/main/java/com/alibaba/nacos/client/config/impl/HttpSimpleClient.java +++ /dev/null @@ -1,305 +0,0 @@ -/* - * 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.impl; - -import com.alibaba.nacos.api.common.Constants; -import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.client.utils.ParamUtil; -import com.alibaba.nacos.common.constant.HttpHeaderConsts; -import com.alibaba.nacos.common.http.client.NacosRestTemplate; -import com.alibaba.nacos.common.utils.IoUtils; -import com.alibaba.nacos.common.utils.MD5Utils; -import com.alibaba.nacos.common.utils.UuidUtils; -import com.alibaba.nacos.common.utils.VersionUtils; - -import java.io.IOException; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.net.URLEncoder; -import java.util.ArrayList; -import java.util.Iterator; -import java.util.List; -import java.util.Map; - -/** - * Http tool. - * - * @author Nacos - * @deprecated Use NacosRestTemplate{@link NacosRestTemplate} unified http client - */ -@Deprecated -public class HttpSimpleClient { - - /** - * Get method. - * - * @param url url - * @param headers headers - * @param paramValues paramValues - * @param encoding encoding - * @param readTimeoutMs readTimeoutMs - * @param isSsl isSsl - * @return result - * @throws IOException io exception - */ - public static HttpResult httpGet(String url, List headers, List paramValues, String encoding, - long readTimeoutMs, boolean isSsl) throws IOException { - String encodedContent = encodingParams(paramValues, encoding); - url += (null == encodedContent) ? "" : ("?" + encodedContent); - if (Limiter - .isLimit(MD5Utils.md5Hex(new StringBuilder(url).append(encodedContent).toString(), Constants.ENCODE))) { - return new HttpResult(NacosException.CLIENT_OVER_THRESHOLD, - "More than client-side current limit threshold"); - } - - HttpURLConnection conn = null; - - try { - conn = (HttpURLConnection) new URL(url).openConnection(); - conn.setRequestMethod("GET"); - conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 100 ? ParamUtil.getConnectTimeout() : 100); - conn.setReadTimeout((int) readTimeoutMs); - List newHeaders = getHeaders(url, headers, paramValues); - setHeaders(conn, newHeaders, encoding); - - conn.connect(); - - int respCode = conn.getResponseCode(); - String resp = null; - - if (HttpURLConnection.HTTP_OK == respCode) { - resp = IoUtils.toString(conn.getInputStream(), encoding); - } else { - resp = IoUtils.toString(conn.getErrorStream(), encoding); - } - return new HttpResult(respCode, conn.getHeaderFields(), resp); - } finally { - IoUtils.closeQuietly(conn); - } - } - - /** - * 发送GET请求. - */ - public static HttpResult httpGet(String url, List headers, List paramValues, String encoding, - long readTimeoutMs) throws IOException { - return httpGet(url, headers, paramValues, encoding, readTimeoutMs, false); - } - - /** - * 发送POST请求. - * - * @param url url - * @param headers 请求Header,可以为null - * @param paramValues 参数,可以为null - * @param encoding URL编码使用的字符集 - * @param readTimeoutMs 响应超时 - * @param isSsl 是否https - * @return result - * @throws IOException io exception - */ - public static HttpResult httpPost(String url, List headers, List paramValues, String encoding, - long readTimeoutMs, boolean isSsl) throws IOException { - String encodedContent = encodingParams(paramValues, encoding); - encodedContent = (null == encodedContent) ? "" : encodedContent; - if (Limiter - .isLimit(MD5Utils.md5Hex(new StringBuilder(url).append(encodedContent).toString(), Constants.ENCODE))) { - return new HttpResult(NacosException.CLIENT_OVER_THRESHOLD, - "More than client-side current limit threshold"); - } - HttpURLConnection conn = null; - try { - conn = (HttpURLConnection) new URL(url).openConnection(); - conn.setRequestMethod("POST"); - conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 3000 ? ParamUtil.getConnectTimeout() : 3000); - conn.setReadTimeout((int) readTimeoutMs); - conn.setDoOutput(true); - conn.setDoInput(true); - List newHeaders = getHeaders(url, headers, paramValues); - setHeaders(conn, newHeaders, encoding); - - conn.getOutputStream().write(encodedContent.getBytes(encoding)); - - int respCode = conn.getResponseCode(); - String resp = null; - - if (HttpURLConnection.HTTP_OK == respCode) { - resp = IoUtils.toString(conn.getInputStream(), encoding); - } else { - resp = IoUtils.toString(conn.getErrorStream(), encoding); - } - return new HttpResult(respCode, conn.getHeaderFields(), resp); - } finally { - IoUtils.closeQuietly(conn); - } - } - - /** - * 发送POST请求. - * - * @param url url - * @param headers 请求Header,可以为null - * @param paramValues 参数,可以为null - * @param encoding URL编码使用的字符集 - * @param readTimeoutMs 响应超时 - * @return result - * @throws IOException io exception - */ - public static HttpResult httpPost(String url, List headers, List paramValues, String encoding, - long readTimeoutMs) throws IOException { - return httpPost(url, headers, paramValues, encoding, readTimeoutMs, false); - } - - /** - * Delete method. - * - * @param url url - * @param headers 请求Header,可以为null - * @param paramValues 参数,可以为null - * @param encoding URL编码使用的字符集 - * @param readTimeoutMs 响应超时 - * @param isSsl 是否https - * @return result - * @throws IOException io exception - */ - public static HttpResult httpDelete(String url, List headers, List paramValues, String encoding, - long readTimeoutMs, boolean isSsl) throws IOException { - String encodedContent = encodingParams(paramValues, encoding); - url += (null == encodedContent) ? "" : ("?" + encodedContent); - if (Limiter - .isLimit(MD5Utils.md5Hex(new StringBuilder(url).append(encodedContent).toString(), Constants.ENCODE))) { - return new HttpResult(NacosException.CLIENT_OVER_THRESHOLD, - "More than client-side current limit threshold"); - } - - HttpURLConnection conn = null; - - try { - conn = (HttpURLConnection) new URL(url).openConnection(); - conn.setRequestMethod("DELETE"); - conn.setConnectTimeout(ParamUtil.getConnectTimeout() > 100 ? ParamUtil.getConnectTimeout() : 100); - conn.setReadTimeout((int) readTimeoutMs); - List newHeaders = getHeaders(url, headers, paramValues); - setHeaders(conn, newHeaders, encoding); - - conn.connect(); - - int respCode = conn.getResponseCode(); - String resp = null; - - if (HttpURLConnection.HTTP_OK == respCode) { - resp = IoUtils.toString(conn.getInputStream(), encoding); - } else { - resp = IoUtils.toString(conn.getErrorStream(), encoding); - } - return new HttpResult(respCode, conn.getHeaderFields(), resp); - } finally { - IoUtils.closeQuietly(conn); - } - } - - /** - * Delete method. - * - * @param url url - * @param headers 请求Header,可以为null - * @param paramValues 参数,可以为null - * @param encoding URL编码使用的字符集 - * @param readTimeoutMs 响应超时 - * @return result - * @throws IOException io exception - */ - public static HttpResult httpDelete(String url, List headers, List paramValues, String encoding, - long readTimeoutMs) throws IOException { - return httpGet(url, headers, paramValues, encoding, readTimeoutMs, false); - } - - private static void setHeaders(HttpURLConnection conn, List headers, String encoding) { - if (null != headers) { - for (Iterator iter = headers.iterator(); iter.hasNext(); ) { - conn.addRequestProperty(iter.next(), iter.next()); - } - } - conn.addRequestProperty(HttpHeaderConsts.CLIENT_VERSION_HEADER, VersionUtils.version); - conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + encoding); - - String ts = String.valueOf(System.currentTimeMillis()); - String token = MD5Utils.md5Hex(ts + ParamUtil.getAppKey(), Constants.ENCODE); - - conn.addRequestProperty(Constants.CLIENT_APPNAME_HEADER, ParamUtil.getAppName()); - conn.addRequestProperty(Constants.CLIENT_REQUEST_TS_HEADER, ts); - conn.addRequestProperty(Constants.CLIENT_REQUEST_TOKEN_HEADER, token); - } - - private static List getHeaders(String url, List headers, List paramValues) - throws IOException { - List newHeaders = new ArrayList(); - newHeaders.add("exConfigInfo"); - newHeaders.add("true"); - newHeaders.add("RequestId"); - newHeaders.add(UuidUtils.generateUuid()); - if (headers != null) { - newHeaders.addAll(headers); - } - return newHeaders; - } - - private static String encodingParams(List paramValues, String encoding) - throws UnsupportedEncodingException { - StringBuilder sb = new StringBuilder(); - if (null == paramValues) { - return null; - } - - for (Iterator iter = paramValues.iterator(); iter.hasNext(); ) { - sb.append(iter.next()).append("="); - sb.append(URLEncoder.encode(iter.next(), encoding)); - if (iter.hasNext()) { - sb.append("&"); - } - } - return sb.toString(); - } - - public static class HttpResult { - - public final int code; - - public final Map> headers; - - public final String content; - - public HttpResult(int code, String content) { - this.code = code; - this.headers = null; - this.content = content; - } - - public HttpResult(int code, Map> headers, String content) { - this.code = code; - this.headers = headers; - this.content = content; - } - - @Override - public String toString() { - return "HttpResult{" + "code=" + code + ", headers=" + headers + ", content='" + content + '\'' + '}'; - } - } - -} diff --git a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java b/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java deleted file mode 100644 index ad913478890..00000000000 --- a/client/src/main/java/com/alibaba/nacos/client/naming/net/HttpClient.java +++ /dev/null @@ -1,248 +0,0 @@ -/* - * 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.naming.net; - -import com.alibaba.nacos.api.common.Constants; -import com.alibaba.nacos.common.http.client.NacosRestTemplate; -import com.alibaba.nacos.common.tls.TlsSystemConfig; -import com.alibaba.nacos.common.utils.HttpMethod; -import com.alibaba.nacos.common.utils.IoUtils; -import com.alibaba.nacos.common.utils.StringUtils; -import com.google.common.net.HttpHeaders; - -import java.io.IOException; -import java.io.InputStream; -import java.io.UnsupportedEncodingException; -import java.net.HttpURLConnection; -import java.net.InetAddress; -import java.net.URL; -import java.net.URLEncoder; -import java.util.Collections; -import java.util.HashMap; -import java.util.Iterator; -import java.util.List; -import java.util.Map; -import java.util.zip.GZIPInputStream; - -import static com.alibaba.nacos.client.utils.LogUtils.NAMING_LOGGER; - -/** - * Http client. - * - * @author nkorange - * @deprecated Use NacosRestTemplate{@link NacosRestTemplate} unified http client - */ -@Deprecated -public class HttpClient { - - public static final int READ_TIME_OUT_MILLIS = Integer - .getInteger("com.alibaba.nacos.client.naming.rtimeout", 50000); - - public static final int CON_TIME_OUT_MILLIS = Integer.getInteger("com.alibaba.nacos.client.naming.ctimeout", 3000); - - private static final boolean ENABLE_HTTPS = Boolean.getBoolean(TlsSystemConfig.TLS_ENABLE); - - static { - // limit max redirection - System.setProperty("http.maxRedirects", "5"); - } - - public static String getPrefix() { - if (ENABLE_HTTPS) { - return "https://"; - } - - return "http://"; - - } - - public static HttpResult httpGet(String url, List headers, Map paramValues, - String encoding) { - return request(url, headers, paramValues, StringUtils.EMPTY, encoding, HttpMethod.GET); - } - - /** - * request. - * - * @param url url - * @param headers headers - * @param paramValues paramValues - * @param body body - * @param encoding encoding - * @param method method - * @return result - */ - public static HttpResult request(String url, List headers, Map paramValues, String body, - String encoding, String method) { - HttpURLConnection conn = null; - try { - String encodedContent = encodingParams(paramValues, encoding); - url += (StringUtils.isEmpty(encodedContent)) ? "" : ("?" + encodedContent); - - conn = (HttpURLConnection) new URL(url).openConnection(); - - setHeaders(conn, headers, encoding); - conn.setConnectTimeout(CON_TIME_OUT_MILLIS); - conn.setReadTimeout(READ_TIME_OUT_MILLIS); - conn.setRequestMethod(method); - conn.setDoOutput(true); - if (StringUtils.isNotBlank(body)) { - byte[] b = body.getBytes(); - conn.setRequestProperty("Content-Length", String.valueOf(b.length)); - conn.getOutputStream().write(b, 0, b.length); - conn.getOutputStream().flush(); - conn.getOutputStream().close(); - } - conn.connect(); - if (NAMING_LOGGER.isDebugEnabled()) { - NAMING_LOGGER.debug("Request from server: " + url); - } - return getResult(conn); - } catch (Exception e) { - try { - if (conn != null) { - NAMING_LOGGER.warn("failed to request " + conn.getURL() + " from " + InetAddress - .getByName(conn.getURL().getHost()).getHostAddress()); - } - } catch (Exception ex) { - NAMING_LOGGER.error("[NA] failed to request ", ex); - //ignore - } - - NAMING_LOGGER.error("[NA] failed to request ", e); - - return new HttpResult(500, e.toString(), Collections.emptyMap()); - } finally { - IoUtils.closeQuietly(conn); - } - } - - private static HttpResult getResult(HttpURLConnection conn) throws IOException { - int respCode = conn.getResponseCode(); - - InputStream inputStream; - if (HttpURLConnection.HTTP_OK == respCode || HttpURLConnection.HTTP_NOT_MODIFIED == respCode - || Constants.WRITE_REDIRECT_CODE == respCode) { - inputStream = conn.getInputStream(); - } else { - inputStream = conn.getErrorStream(); - } - - Map respHeaders = new HashMap(conn.getHeaderFields().size()); - for (Map.Entry> entry : conn.getHeaderFields().entrySet()) { - respHeaders.put(entry.getKey(), entry.getValue().get(0)); - } - - String encodingGzip = "gzip"; - - if (encodingGzip.equals(respHeaders.get(HttpHeaders.CONTENT_ENCODING))) { - inputStream = new GZIPInputStream(inputStream); - } - HttpResult httpResult = new HttpResult(respCode, IoUtils.toString(inputStream, getCharset(conn)), respHeaders); - - //InputStream from HttpURLConnection can be closed automatically,but new GZIPInputStream can't be closed automatically - //so needs to close it manually - if (inputStream instanceof GZIPInputStream) { - inputStream.close(); - } - return httpResult; - } - - private static String getCharset(HttpURLConnection conn) { - String contentType = conn.getContentType(); - if (StringUtils.isEmpty(contentType)) { - return "UTF-8"; - } - - String[] values = contentType.split(";"); - if (values.length == 0) { - return "UTF-8"; - } - - String charset = "UTF-8"; - for (String value : values) { - value = value.trim(); - - if (value.toLowerCase().startsWith("charset=")) { - charset = value.substring("charset=".length()); - } - } - - return charset; - } - - private static void setHeaders(HttpURLConnection conn, List headers, String encoding) { - if (null != headers) { - for (Iterator iter = headers.iterator(); iter.hasNext(); ) { - conn.addRequestProperty(iter.next(), iter.next()); - } - } - - conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + encoding); - conn.addRequestProperty("Accept-Charset", encoding); - } - - private static String encodingParams(Map params, String encoding) - throws UnsupportedEncodingException { - if (null == params || params.isEmpty()) { - return ""; - } - - params.put("encoding", encoding); - StringBuilder sb = new StringBuilder(); - - for (Map.Entry entry : params.entrySet()) { - if (StringUtils.isEmpty(entry.getValue())) { - continue; - } - - sb.append(entry.getKey()).append("="); - sb.append(URLEncoder.encode(entry.getValue(), encoding)); - sb.append("&"); - } - - if (sb.length() > 0) { - sb = sb.deleteCharAt(sb.length() - 1); - } - return sb.toString(); - } - - public static class HttpResult { - - public final int code; - - public final String content; - - private final Map respHeaders; - - public HttpResult(int code, String content, Map respHeaders) { - this.code = code; - this.content = content; - this.respHeaders = respHeaders; - } - - public String getHeader(String name) { - return respHeaders.get(name); - } - - @Override - public String toString() { - return "HttpResult{" + "code=" + code + ", content='" + content + '\'' + ", respHeaders=" + respHeaders - + '}'; - } - } -} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/BaseHttpClient.java b/common/src/main/java/com/alibaba/nacos/common/http/BaseHttpClient.java deleted file mode 100644 index 18bd1782d04..00000000000 --- a/common/src/main/java/com/alibaba/nacos/common/http/BaseHttpClient.java +++ /dev/null @@ -1,124 +0,0 @@ -/* - * 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.common.http; - -import com.alibaba.nacos.common.http.handler.ResponseHandler; -import com.alibaba.nacos.common.http.param.Header; -import com.alibaba.nacos.common.http.param.Query; -import com.alibaba.nacos.common.model.RestResult; -import org.apache.http.HttpResponse; -import org.apache.http.client.methods.CloseableHttpResponse; -import org.apache.http.client.methods.HttpEntityEnclosingRequestBase; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.client.methods.HttpUriRequest; -import org.apache.http.client.utils.HttpClientUtils; -import org.apache.http.concurrent.FutureCallback; -import org.apache.http.impl.client.CloseableHttpClient; -import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; -import org.apache.http.util.EntityUtils; - -import java.lang.reflect.Type; -import java.net.URI; - -/** - * Base http client. - * - * @author liaochuntao - * @deprecated Refer to the new {@link com.alibaba.nacos.common.http.client.request.HttpClientRequest} - */ -@Deprecated -public abstract class BaseHttpClient { - - protected RestResult execute(CloseableHttpClient httpClient, final Type type, HttpUriRequest request) - throws Exception { - CloseableHttpResponse response = httpClient.execute(request); - try { - final String body = EntityUtils.toString(response.getEntity()); - RestResult data = ResponseHandler.convert(body, type); - return data; - } finally { - HttpClientUtils.closeQuietly(response); - } - } - - protected void execute(CloseableHttpAsyncClient httpAsyncClient, final Type type, final Callback callback, - final HttpUriRequest request) { - if (!httpAsyncClient.isRunning()) { - throw new IllegalArgumentException("httpAsyncClient already shutdown"); - } - httpAsyncClient.execute(request, new FutureCallback() { - - @Override - public void completed(HttpResponse response) { - try { - final String body = EntityUtils.toString(response.getEntity()); - RestResult data = ResponseHandler.convert(body, type); - data.setCode(response.getStatusLine().getStatusCode()); - callback.onReceive(data); - } catch (Throwable e) { - callback.onError(e); - } - } - - @Override - public void failed(Exception ex) { - callback.onError(ex); - } - - @Override - public void cancelled() { - callback.onCancel(); - } - }); - } - - protected String buildUrl(String baseUrl, Query query) { - if (query.isEmpty()) { - return baseUrl; - } - return baseUrl + "?" + query.toQueryUrl(); - } - - protected HttpRequestBase build(String url, Header header, String method) throws Exception { - return build(url, header, null, method); - } - - protected HttpRequestBase build(String url, Header header, Object body, String method) throws Exception { - - final BaseHttpMethod httpMethod = BaseHttpMethod.sourceOf(method); - final HttpRequestBase httpRequestBase = httpMethod.init(url); - HttpUtils.initRequestHeader(httpRequestBase, header); - HttpUtils.initRequestEntity(httpRequestBase, body, header); - return httpRequestBase; - } - - public static class HttpGetWithEntity extends HttpEntityEnclosingRequestBase { - - public static final String METHOD_NAME = "GET"; - - public HttpGetWithEntity(String url) { - super(); - setURI(URI.create(url)); - } - - @Override - public String getMethod() { - return METHOD_NAME; - } - } - -} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/HttpClientManager.java b/common/src/main/java/com/alibaba/nacos/common/http/HttpClientManager.java deleted file mode 100644 index 47e0c39b574..00000000000 --- a/common/src/main/java/com/alibaba/nacos/common/http/HttpClientManager.java +++ /dev/null @@ -1,88 +0,0 @@ -/* - * 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.common.http; - -import com.alibaba.nacos.common.utils.ExceptionUtil; -import com.alibaba.nacos.common.utils.ThreadUtils; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.impl.client.HttpClients; -import org.apache.http.impl.nio.client.HttpAsyncClients; -import org.slf4j.Logger; -import org.slf4j.LoggerFactory; - -import java.util.concurrent.atomic.AtomicBoolean; - -/** - * Use the same HttpClient object in the same space. - * - * @author liaochuntao - * @deprecated Refer to the new {@link HttpClientBeanHolder} - */ -@Deprecated -public class HttpClientManager { - - private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientManager.class); - - private static final int TIMEOUT = Integer.getInteger("nacos.http.timeout", 5000); - - private static final RequestConfig DEFAULT_CONFIG = RequestConfig.custom().setConnectTimeout(TIMEOUT) - .setSocketTimeout(TIMEOUT << 1).build(); - - private static final NSyncHttpClient SYNC_HTTP_CLIENT = new NacosSyncHttpClient( - HttpClients.custom().setDefaultRequestConfig(DEFAULT_CONFIG).build()); - - private static final NAsyncHttpClient ASYNC_HTTP_CLIENT = new NacosAsyncHttpClient( - HttpAsyncClients.custom().setDefaultRequestConfig(DEFAULT_CONFIG).build()); - - private static final AtomicBoolean ALREADY_SHUTDOWN = new AtomicBoolean(false); - - static { - ThreadUtils.addShutdownHook(new Runnable() { - @Override - public void run() { - shutdown(); - } - }); - - } - - public static NSyncHttpClient getSyncHttpClient() { - return SYNC_HTTP_CLIENT; - } - - public static NAsyncHttpClient getAsyncHttpClient() { - return ASYNC_HTTP_CLIENT; - } - - /** - * Shutdown http client manager and close http client. - */ - public static void shutdown() { - if (!ALREADY_SHUTDOWN.compareAndSet(false, true)) { - return; - } - LOGGER.warn("[HttpClientManager] Start destroying HttpClient"); - try { - SYNC_HTTP_CLIENT.close(); - ASYNC_HTTP_CLIENT.close(); - } catch (Exception ex) { - LOGGER.error("An exception occurred when the HTTP client was closed : {}", ExceptionUtil.getStackTrace(ex)); - } - LOGGER.warn("[HttpClientManager] Destruction of the end"); - } - -} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/NAsyncHttpClient.java b/common/src/main/java/com/alibaba/nacos/common/http/NAsyncHttpClient.java deleted file mode 100644 index b531b2731ed..00000000000 --- a/common/src/main/java/com/alibaba/nacos/common/http/NAsyncHttpClient.java +++ /dev/null @@ -1,95 +0,0 @@ -/* - * 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.common.http; - -import com.alibaba.nacos.common.http.param.Header; -import com.alibaba.nacos.common.http.param.Query; - -import java.lang.reflect.Type; - -/** - * Nacos async http client interface. - * - * @author liaochuntao - * @deprecated Refer to the new {@link com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate} - */ -@Deprecated -@SuppressWarnings("all") -public interface NAsyncHttpClient extends NHttpClient { - - /** - * http get - * - * @param url url - * @param header http header param - * @param query http query param - * @param token return type - * @param callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - */ - void get(String url, Header header, Query query, Type token, Callback callback) throws Exception; - - /** - * get request, may be pulling a lot of data - * - * @param url url - * @param header http header param - * @param query http query param - * @param body get with body - * @param token return type - * @param callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - */ - void getLarge(String url, Header header, Query query, Object body, Type token, Callback callback) - throws Exception; - - /** - * http delete - * - * @param url url - * @param header http header param - * @param query http query param - * @param token return type - * @param callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - */ - void delete(String url, Header header, Query query, Type token, Callback callback) throws Exception; - - /** - * http put - * - * @param url url - * @param header http header param - * @param query http query param - * @param body http body param - * @param token return type - * @param callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - */ - void put(String url, Header header, Query query, Object body, Type token, Callback callback) - throws Exception; - - /** - * http post - * - * @param url url - * @param header http header param - * @param query http query param - * @param body http body param - * @param token return type - * @param callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - */ - void post(String url, Header header, Query query, Object body, Type token, Callback callback) - throws Exception; - -} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/NHttpClient.java b/common/src/main/java/com/alibaba/nacos/common/http/NHttpClient.java deleted file mode 100644 index a6dbd7d6a86..00000000000 --- a/common/src/main/java/com/alibaba/nacos/common/http/NHttpClient.java +++ /dev/null @@ -1,31 +0,0 @@ -/* - * 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.common.http; - -import java.io.Closeable; - -/** - * Nacos http client interface. - * - * @author liaochuntao - * @deprecated Refer to the new {@link com.alibaba.nacos.common.http.client.request.HttpClientRequest} - */ -@Deprecated -@SuppressWarnings("PMD.ClassNamingShouldBeCamelRule") -public interface NHttpClient extends Closeable { - -} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/NSyncHttpClient.java b/common/src/main/java/com/alibaba/nacos/common/http/NSyncHttpClient.java deleted file mode 100644 index f485e5b83fb..00000000000 --- a/common/src/main/java/com/alibaba/nacos/common/http/NSyncHttpClient.java +++ /dev/null @@ -1,98 +0,0 @@ -/* - * 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.common.http; - -import com.alibaba.nacos.common.http.param.Header; -import com.alibaba.nacos.common.http.param.Query; -import com.alibaba.nacos.common.model.RestResult; - -import java.lang.reflect.Type; - -/** - * Nacos sync http client. - * - * @author liaochuntao - * @deprecated Refer to the new {@link com.alibaba.nacos.common.http.client.NacosRestTemplate} - */ -@Deprecated -@SuppressWarnings("all") -public interface NSyncHttpClient extends NHttpClient { - - /** - * http get - * - * @param url url - * @param header http header param - * @param query http query param - * @param token return type - * @return {@link RestResult } - * @throws Exception - */ - RestResult get(String url, Header header, Query query, Type token) throws Exception; - - /** - * get request, may be pulling a lot of data - * - * @param url url - * @param header http header param - * @param query http query param - * @param body get with body - * @param token return type - * @return {@link RestResult } - * @throws Exception - */ - RestResult getLarge(String url, Header header, Query query, Object body, Type token) throws Exception; - - /** - * http delete - * - * @param url url - * @param header http header param - * @param query http query param - * @param token return type - * @return {@link RestResult } - * @throws Exception - */ - RestResult delete(String url, Header header, Query query, Type token) throws Exception; - - /** - * http put - * - * @param url url - * @param header http header param - * @param query http query param - * @param body http body param - * @param token return type - * @return {@link RestResult} - * @throws Exception - */ - RestResult put(String url, Header header, Query query, Object body, Type token) throws Exception; - - /** - * http post - * - * @param url url - * @param header http header param - * @param query http query param - * @param body http body param - * @param token return type - * @return {@link RestResult} - * @throws Exception - */ - RestResult post(String url, Header header, Query query, Object body, Type token) throws Exception; - -} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/NacosAsyncHttpClient.java b/common/src/main/java/com/alibaba/nacos/common/http/NacosAsyncHttpClient.java deleted file mode 100644 index 0fe7c3944ed..00000000000 --- a/common/src/main/java/com/alibaba/nacos/common/http/NacosAsyncHttpClient.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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.common.http; - -import com.alibaba.nacos.common.http.param.Header; -import com.alibaba.nacos.common.http.param.Query; -import com.alibaba.nacos.common.utils.HttpMethod; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; - -import java.io.IOException; -import java.lang.reflect.Type; - -/** - * Nacos async http client. - * - * @author liaochuntao - * @deprecated Refer to the new {@link com.alibaba.nacos.common.http.client.request.DefaultAsyncHttpClientRequest} - */ -@Deprecated -class NacosAsyncHttpClient extends BaseHttpClient implements NAsyncHttpClient { - - private CloseableHttpAsyncClient asyncClient; - - NacosAsyncHttpClient(CloseableHttpAsyncClient asyncClient) { - this.asyncClient = asyncClient; - this.asyncClient.start(); - } - - @Override - public void get(final String url, final Header header, final Query query, final Type token, - final Callback callback) throws Exception { - HttpRequestBase requestBase = build(buildUrl(url, query), header, HttpMethod.GET); - execute(asyncClient, token, callback, requestBase); - } - - @Override - public void getLarge(final String url, final Header header, final Query query, final Object body, - final Type token, final Callback callback) throws Exception { - HttpRequestBase requestBase = build(buildUrl(url, query), header, body, HttpMethod.GET_LARGE); - execute(asyncClient, token, callback, requestBase); - } - - @Override - public void delete(final String url, final Header header, final Query query, final Type token, - final Callback callback) throws Exception { - HttpRequestBase requestBase = build(buildUrl(url, query), header, HttpMethod.DELETE); - execute(asyncClient, token, callback, requestBase); - } - - @Override - public void put(final String url, final Header header, final Query query, final Object body, final Type token, - final Callback callback) throws Exception { - HttpRequestBase requestBase = build(buildUrl(url, query), header, body, HttpMethod.PUT); - execute(asyncClient, token, callback, requestBase); - } - - @Override - public void post(final String url, final Header header, final Query query, final Object body, final Type token, - final Callback callback) throws Exception { - HttpRequestBase requestBase = build(buildUrl(url, query), header, body, HttpMethod.POST); - execute(asyncClient, token, callback, requestBase); - } - - @Override - public void close() throws IOException { - asyncClient.close(); - } -} diff --git a/common/src/main/java/com/alibaba/nacos/common/http/NacosSyncHttpClient.java b/common/src/main/java/com/alibaba/nacos/common/http/NacosSyncHttpClient.java deleted file mode 100644 index 2b36b988500..00000000000 --- a/common/src/main/java/com/alibaba/nacos/common/http/NacosSyncHttpClient.java +++ /dev/null @@ -1,83 +0,0 @@ -/* - * 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.common.http; - -import com.alibaba.nacos.common.http.param.Header; -import com.alibaba.nacos.common.http.param.Query; -import com.alibaba.nacos.common.model.RestResult; -import com.alibaba.nacos.common.utils.HttpMethod; -import org.apache.http.client.methods.HttpRequestBase; -import org.apache.http.impl.client.CloseableHttpClient; - -import java.io.IOException; -import java.lang.reflect.Type; - -/** - * Nacos sync http client. - * - * @author liaochuntao - * @deprecated Refer to the new {@link com.alibaba.nacos.common.http.client.request.JdkHttpClientRequest} - */ -@Deprecated -class NacosSyncHttpClient extends BaseHttpClient implements NSyncHttpClient { - - private CloseableHttpClient client; - - NacosSyncHttpClient(CloseableHttpClient client) { - this.client = client; - } - - @Override - public RestResult get(final String url, final Header header, final Query query, final Type token) - throws Exception { - HttpRequestBase requestBase = build(buildUrl(url, query), header, HttpMethod.GET); - return execute(client, token, requestBase); - } - - @Override - public RestResult getLarge(String url, Header header, Query query, Object body, Type token) - throws Exception { - HttpRequestBase requestBase = build(buildUrl(url, query), header, body, HttpMethod.GET_LARGE); - return execute(client, token, requestBase); - } - - @Override - public RestResult delete(final String url, final Header header, final Query query, final Type token) - throws Exception { - HttpRequestBase requestBase = build(buildUrl(url, query), header, HttpMethod.DELETE); - return execute(client, token, requestBase); - } - - @Override - public RestResult put(final String url, final Header header, final Query query, final Object body, - final Type token) throws Exception { - HttpRequestBase requestBase = build(buildUrl(url, query), header, body, HttpMethod.PUT); - return execute(client, token, requestBase); - } - - @Override - public RestResult post(final String url, final Header header, final Query query, final Object body, - final Type token) throws Exception { - HttpRequestBase requestBase = build(buildUrl(url, query), header, body, HttpMethod.POST); - return execute(client, token, requestBase); - } - - @Override - public void close() throws IOException { - client.close(); - } -} diff --git a/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java b/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java index 12804721bd4..9ea0a28f556 100644 --- a/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java +++ b/core/src/main/java/com/alibaba/nacos/core/code/StartingSpringApplicationRunListener.java @@ -19,7 +19,6 @@ import com.alibaba.nacos.common.executor.ExecutorFactory; import com.alibaba.nacos.common.executor.NameThreadFactory; import com.alibaba.nacos.common.executor.ThreadPoolManager; -import com.alibaba.nacos.common.http.HttpClientManager; import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.sys.file.WatchFileCenter; import com.alibaba.nacos.sys.utils.ApplicationUtils; @@ -142,8 +141,6 @@ public void failed(ConfigurableApplicationContext context, Throwable exception) logFilePath(); LOGGER.error("Startup errors : {}", exception); - - HttpClientManager.shutdown(); ThreadPoolManager.shutdown(); WatchFileCenter.shutdown(); NotifyCenter.shutdown(); diff --git a/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java b/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java index 50f3a02e5a6..76467796965 100644 --- a/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java +++ b/core/src/main/java/com/alibaba/nacos/core/controller/NacosClusterController.java @@ -17,9 +17,9 @@ package com.alibaba.nacos.core.controller; import com.alibaba.nacos.common.http.Callback; -import com.alibaba.nacos.common.http.HttpClientManager; +import com.alibaba.nacos.common.http.HttpClientBeanHolder; import com.alibaba.nacos.common.http.HttpUtils; -import com.alibaba.nacos.common.http.NAsyncHttpClient; +import com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate; import com.alibaba.nacos.common.http.param.Header; import com.alibaba.nacos.common.http.param.Query; import com.alibaba.nacos.common.model.RestResult; @@ -152,7 +152,7 @@ public RestResult switchLookup(@RequestParam(name = "type") String type) public RestResult leave(@RequestBody Collection params) throws Exception { Collection memberList = MemberUtils.multiParse(params); memberManager.memberLeave(memberList); - final NAsyncHttpClient asyncHttpClient = HttpClientManager.getAsyncHttpClient(); + final NacosAsyncRestTemplate nacosAsyncRestTemplate = HttpClientBeanHolder.getNacosAsyncRestTemplate(Loggers.CLUSTER); final GenericType> genericType = new GenericType>() { }; final Collection notifyList = memberManager.allMembersWithoutSelf(); @@ -162,7 +162,7 @@ public RestResult leave(@RequestBody Collection params) throws E final String url = HttpUtils .buildUrl(false, member.getAddress(), ApplicationUtils.getContextPath(), Commons.NACOS_CORE_CONTEXT, "/cluster/server/leave"); - asyncHttpClient.post(url, Header.EMPTY, Query.EMPTY, params, genericType.getType(), new Callback() { + nacosAsyncRestTemplate.post(url, Header.EMPTY, Query.EMPTY, params, genericType.getType(), new Callback() { @Override public void onReceive(RestResult result) { try {