diff --git a/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java b/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java index 31ee7999faa..0e16159ff96 100644 --- a/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java +++ b/common/src/main/java/com/alibaba/nacos/common/http/client/NacosAsyncRestTemplate.java @@ -61,10 +61,8 @@ public NacosAsyncRestTemplate(Logger logger, AsyncHttpClientRequest clientReques * @param header http header param * @param query http query param * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - * @throws Exception ex */ - public void get(String url, Header header, Query query, Type responseType, Callback callback) - throws Exception { + public void get(String url, Header header, Query query, Type responseType, Callback callback) { execute(url, HttpMethod.GET, new RequestHttpEntity(header, query), responseType, callback); } @@ -81,10 +79,9 @@ public void get(String url, Header header, Query query, Type responseType, C * @param paramValues paramValues * @param responseType return type * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - * @throws Exception ex */ public void get(String url, Header header, Map paramValues, Type responseType, - Callback callback) throws Exception { + Callback callback) { execute(url, HttpMethod.GET, new RequestHttpEntity(header, Query.newInstance().initParams(paramValues)), responseType, callback); } @@ -104,10 +101,9 @@ public void get(String url, Header header, Map paramValues, * @param body get with body * @param responseType return type * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - * @throws Exception ex */ public void getLarge(String url, Header header, Query query, Object body, Type responseType, - Callback callback) throws Exception { + Callback callback) { execute(url, HttpMethod.GET_LARGE, new RequestHttpEntity(header, query, body), responseType, callback); } @@ -124,10 +120,8 @@ public void getLarge(String url, Header header, Query query, Object body, Ty * @param query http query param * @param responseType return type * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - * @throws Exception ex */ - public void delete(String url, Header header, Query query, Type responseType, Callback callback) - throws Exception { + public void delete(String url, Header header, Query query, Type responseType, Callback callback) { execute(url, HttpMethod.DELETE, new RequestHttpEntity(header, query), responseType, callback); } @@ -147,10 +141,8 @@ public void delete(String url, Header header, Query query, Type responseType * @param body http body param * @param responseType return type * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - * @throws Exception ex */ - public void put(String url, Header header, Query query, Object body, Type responseType, Callback callback) - throws Exception { + public void put(String url, Header header, Query query, Object body, Type responseType, Callback callback) { execute(url, HttpMethod.PUT, new RequestHttpEntity(header, query, body), responseType, callback); } @@ -171,10 +163,9 @@ public void put(String url, Header header, Query query, Object body, Type re * @param body http body param * @param responseType return type * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - * @throws Exception ex */ public void putJson(String url, Header header, Map paramValues, String body, Type responseType, - Callback callback) throws Exception { + Callback callback) { execute(url, HttpMethod.PUT, new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_JSON), Query.newInstance().initParams(paramValues), body), responseType, callback); } @@ -196,10 +187,9 @@ public void putJson(String url, Header header, Map paramValu * @param bodyValues http body param * @param responseType return type * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - * @throws Exception ex */ public void putForm(String url, Header header, Query query, Map bodyValues, Type responseType, - Callback callback) throws Exception { + Callback callback) { execute(url, HttpMethod.PUT, new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyValues), responseType, callback); @@ -222,10 +212,9 @@ public void putForm(String url, Header header, Query query, Map void putForm(String url, Header header, Map paramValues, Map bodyValues, - Type responseType, Callback callback) throws Exception { + Type responseType, Callback callback) { execute(url, HttpMethod.PUT, new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), Query.newInstance().initParams(paramValues), bodyValues), responseType, callback); } @@ -246,10 +235,8 @@ public void putForm(String url, Header header, Map paramValu * @param body http body param * @param responseType return type * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - * @throws Exception ex */ - public void post(String url, Header header, Query query, Object body, Type responseType, Callback callback) - throws Exception { + public void post(String url, Header header, Query query, Object body, Type responseType, Callback callback) { execute(url, HttpMethod.POST, new RequestHttpEntity(header, query, body), responseType, callback); } @@ -270,10 +257,9 @@ public void post(String url, Header header, Query query, Object body, Type r * @param body http body param * @param responseType return type * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - * @throws Exception ex */ public void postJson(String url, Header header, Map paramValues, String body, Type responseType, - Callback callback) throws Exception { + Callback callback) { execute(url, HttpMethod.POST, new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_JSON), Query.newInstance().initParams(paramValues), body), responseType, callback); } @@ -295,10 +281,9 @@ public void postJson(String url, Header header, Map paramVal * @param bodyValues http body param * @param responseType return type * @param callback callback {@link Callback#onReceive(com.alibaba.nacos.common.model.RestResult)} - * @throws Exception ex */ public void postForm(String url, Header header, Query query, Map bodyValues, Type responseType, - Callback callback) throws Exception { + Callback callback) { execute(url, HttpMethod.POST, new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), query, bodyValues), responseType, callback); @@ -321,10 +306,9 @@ public void postForm(String url, Header header, Query query, Map void postForm(String url, Header header, Map paramValues, Map bodyValues, - Type responseType, Callback callback) throws Exception { + Type responseType, Callback callback) { execute(url, HttpMethod.POST, new RequestHttpEntity(header.setContentType(MediaType.APPLICATION_FORM_URLENCODED), Query.newInstance().initParams(paramValues), bodyValues), responseType, callback); @@ -333,13 +317,18 @@ public void postForm(String url, Header header, Map paramVal @SuppressWarnings("unchecked") private void execute(String url, String httpMethod, RequestHttpEntity requestEntity, Type type, - Callback callback) throws Exception { - URI uri = HttpUtils.buildUri(url, requestEntity.getQuery()); - if (logger.isDebugEnabled()) { - logger.debug("HTTP method: {}, url: {}, body: {}", httpMethod, uri, requestEntity.getBody()); + Callback callback) { + try { + URI uri = HttpUtils.buildUri(url, requestEntity.getQuery()); + if (logger.isDebugEnabled()) { + logger.debug("HTTP method: {}, url: {}, body: {}", httpMethod, uri, requestEntity.getBody()); + } + ResponseHandler responseHandler = super.selectResponseHandler(type); + clientRequest.execute(uri, httpMethod, requestEntity, responseHandler, callback); + } catch (Exception e) { + // When an exception occurs, use Callback to pass it instead of throw it directly. + callback.onError(e); } - ResponseHandler responseHandler = super.selectResponseHandler(type); - clientRequest.execute(uri, httpMethod, requestEntity, responseHandler, callback); } /** diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ClientIpWhiteList.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ClientIpWhiteList.java index 75d8a816dbb..11b31bc1f24 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ClientIpWhiteList.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ClientIpWhiteList.java @@ -16,8 +16,8 @@ package com.alibaba.nacos.config.server.service; +import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.config.server.model.AclInfo; -import com.alibaba.nacos.config.server.utils.JSONUtils; import org.apache.commons.lang3.StringUtils; import org.springframework.stereotype.Service; @@ -76,7 +76,7 @@ public static void load(String content) { } DEFAULT_LOG.warn("[clientIpWhiteList] {}", content); try { - AclInfo acl = (AclInfo) JSONUtils.deserializeObject(content, AclInfo.class); + AclInfo acl = JacksonUtils.toObj(content, AclInfo.class); isOpen = acl.getIsOpen(); CLIENT_IP_WHITELIST.set(acl.getIps()); } catch (Exception ioe) { diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java index 892e21f821a..157f373a532 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/ConfigSubService.java @@ -16,21 +16,20 @@ package com.alibaba.nacos.config.server.service; +import com.alibaba.nacos.common.model.RestResult; +import com.alibaba.nacos.common.utils.JacksonUtils; import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.model.SampleResult; import com.alibaba.nacos.config.server.service.notify.NotifyService; import com.alibaba.nacos.config.server.utils.ConfigExecutor; -import com.alibaba.nacos.config.server.utils.JSONUtils; import com.alibaba.nacos.config.server.utils.LogUtil; import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.core.utils.ApplicationUtils; -import com.fasterxml.jackson.core.type.TypeReference; import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Service; -import java.net.HttpURLConnection; import java.net.URLEncoder; import java.util.ArrayList; import java.util.Collection; @@ -178,19 +177,15 @@ public SampleResult call() throws Exception { } String urlAll = getUrl(ip, url) + "?" + paramUrl; - com.alibaba.nacos.config.server.service.notify.NotifyService.HttpResult result = NotifyService + RestResult result = NotifyService .invokeURL(urlAll, null, Constants.ENCODE); // Http code 200 - if (result.code == HttpURLConnection.HTTP_OK) { - String json = result.content; - SampleResult resultObj = JSONUtils.deserializeObject(json, new TypeReference() { - }); - return resultObj; - + if (result.ok()) { + return JacksonUtils.toObj(result.getData(), SampleResult.class); } else { - LogUtil.DEFAULT_LOG.info("Can not get clientInfo from {} with {}", ip, result.code); + LogUtil.DEFAULT_LOG.info("Can not get clientInfo from {} with {}", ip, result.getData()); return null; } } catch (Exception e) { diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java index c7824729496..f38774bf551 100644 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/AsyncNotifyService.java @@ -16,6 +16,11 @@ package com.alibaba.nacos.config.server.service.notify; +import com.alibaba.nacos.common.http.Callback; +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; import com.alibaba.nacos.common.notify.Event; import com.alibaba.nacos.common.notify.NotifyCenter; import com.alibaba.nacos.common.notify.listener.Subscriber; @@ -25,20 +30,11 @@ import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; import com.alibaba.nacos.config.server.utils.ConfigExecutor; import com.alibaba.nacos.config.server.utils.LogUtil; -import com.alibaba.nacos.config.server.utils.PropertyUtil; import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.core.utils.ApplicationUtils; import com.alibaba.nacos.core.utils.InetUtils; import org.apache.commons.lang3.StringUtils; -import org.apache.http.HttpResponse; -import org.apache.http.HttpStatus; -import org.apache.http.client.config.RequestConfig; -import org.apache.http.client.methods.HttpGet; -import org.apache.http.client.utils.HttpClientUtils; -import org.apache.http.concurrent.FutureCallback; -import org.apache.http.impl.nio.client.CloseableHttpAsyncClient; -import org.apache.http.impl.nio.client.HttpAsyncClients; import org.slf4j.Logger; import org.slf4j.LoggerFactory; import org.springframework.beans.factory.annotation.Autowired; @@ -63,7 +59,6 @@ public class AsyncNotifyService { @Autowired public AsyncNotifyService(ServerMemberManager memberManager) { this.memberManager = memberManager; - httpclient.start(); // Register ConfigDataChangeEvent to NotifyCenter. NotifyCenter.registerToPublisher(ConfigDataChangeEvent.class, NotifyCenter.ringBufferSize); @@ -89,7 +84,7 @@ public void onEvent(Event event) { queue.add(new NotifySingleTask(dataId, group, tenant, tag, dumpTs, member.getAddress(), evt.isBeta)); } - ConfigExecutor.executeAsyncNotify(new AsyncTask(httpclient, queue)); + ConfigExecutor.executeAsyncNotify(new AsyncTask(nacosAsyncRestTemplate, queue)); } } @@ -100,12 +95,7 @@ public Class subscribeType() { }); } - private RequestConfig requestConfig = RequestConfig.custom() - .setConnectTimeout(PropertyUtil.getNotifyConnectTimeout()) - .setSocketTimeout(PropertyUtil.getNotifySocketTimeout()).build(); - - private CloseableHttpAsyncClient httpclient = HttpAsyncClients.custom().setDefaultRequestConfig(requestConfig) - .build(); + private final NacosAsyncRestTemplate nacosAsyncRestTemplate = HttpClientManager.getNacosAsyncRestTemplate(); private static final Logger LOGGER = LoggerFactory.getLogger(AsyncNotifyService.class); @@ -113,8 +103,12 @@ public Class subscribeType() { class AsyncTask implements Runnable { - public AsyncTask(CloseableHttpAsyncClient httpclient, Queue queue) { - this.httpclient = httpclient; + private Queue queue; + + private NacosAsyncRestTemplate restTemplate; + + public AsyncTask(NacosAsyncRestTemplate restTemplate, Queue queue) { + this.restTemplate = restTemplate; this.queue = queue; } @@ -138,52 +132,47 @@ private void executeAsyncInvoke() { // get delay time and set fail count to the task asyncTaskExecute(task); } else { - HttpGet request = new HttpGet(task.url); - request.setHeader(NotifyService.NOTIFY_HEADER_LAST_MODIFIED, - String.valueOf(task.getLastModified())); - request.setHeader(NotifyService.NOTIFY_HEADER_OP_HANDLE_IP, InetUtils.getSelfIp()); + Header header = Header.newInstance(); + header.addParam(NotifyService.NOTIFY_HEADER_LAST_MODIFIED, String.valueOf(task.getLastModified())); + header.addParam(NotifyService.NOTIFY_HEADER_OP_HANDLE_IP, InetUtils.getSelfIp()); if (task.isBeta) { - request.setHeader("isBeta", "true"); + header.addParam("isBeta", "true"); } - httpclient.execute(request, new AsyncNotifyCallBack(httpclient, task)); + restTemplate.get(task.url, header, Query.EMPTY, String.class, new AsyncNotifyCallBack(task)); } } } } - - private Queue queue; - - private CloseableHttpAsyncClient httpclient; - } private void asyncTaskExecute(NotifySingleTask task) { int delay = getDelayTime(task); Queue queue = new LinkedList(); queue.add(task); - AsyncTask asyncTask = new AsyncTask(httpclient, queue); + AsyncTask asyncTask = new AsyncTask(nacosAsyncRestTemplate, queue); ConfigExecutor.scheduleAsyncNotify(asyncTask, delay, TimeUnit.MILLISECONDS); } - class AsyncNotifyCallBack implements FutureCallback { + class AsyncNotifyCallBack implements Callback { + + private NotifySingleTask task; - public AsyncNotifyCallBack(CloseableHttpAsyncClient httpClient, NotifySingleTask task) { + public AsyncNotifyCallBack(NotifySingleTask task) { this.task = task; - this.httpClient = httpClient; } @Override - public void completed(HttpResponse response) { + public void onReceive(RestResult result) { long delayed = System.currentTimeMillis() - task.getLastModified(); - if (response.getStatusLine().getStatusCode() == HttpStatus.SC_OK) { + if (result.ok()) { ConfigTraceService.logNotifyEvent(task.getDataId(), task.getGroup(), task.getTenant(), null, task.getLastModified(), InetUtils.getSelfIp(), ConfigTraceService.NOTIFY_EVENT_OK, delayed, task.target); } else { LOGGER.error("[notify-error] target:{} dataId:{} group:{} ts:{} code:{}", task.target, task.getDataId(), - task.getGroup(), task.getLastModified(), response.getStatusLine().getStatusCode()); + task.getGroup(), task.getLastModified(), result.getCode()); ConfigTraceService.logNotifyEvent(task.getDataId(), task.getGroup(), task.getTenant(), null, task.getLastModified(), InetUtils.getSelfIp(), ConfigTraceService.NOTIFY_EVENT_ERROR, delayed, task.target); @@ -197,11 +186,10 @@ public void completed(HttpResponse response) { MetricsMonitor.getConfigNotifyException().increment(); } - HttpClientUtils.closeQuietly(response); } @Override - public void failed(Exception ex) { + public void onError(Throwable ex) { long delayed = System.currentTimeMillis() - task.getLastModified(); LOGGER.error("[notify-exception] target:{} dataId:{} group:{} ts:{} ex:{}", task.target, task.getDataId(), @@ -219,7 +207,7 @@ public void failed(Exception ex) { } @Override - public void cancelled() { + public void onCancel() { LogUtil.NOTIFY_LOG.error("[notify-exception] target:{} dataId:{} group:{} ts:{} method:{}", task.target, task.getDataId(), task.getGroup(), task.getLastModified(), "CANCELED"); @@ -231,10 +219,6 @@ public void cancelled() { MetricsMonitor.getConfigNotifyException().increment(); } - - private NotifySingleTask task; - - private CloseableHttpAsyncClient httpClient; } static class NotifySingleTask extends NotifyTask { diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/HttpClientManager.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/HttpClientManager.java new file mode 100644 index 00000000000..9a9f447745e --- /dev/null +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/HttpClientManager.java @@ -0,0 +1,109 @@ +/* + * 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.config.server.service.notify; + +import com.alibaba.nacos.common.http.AbstractHttpClientFactory; +import com.alibaba.nacos.common.http.HttpClientBeanHolder; +import com.alibaba.nacos.common.http.HttpClientConfig; +import com.alibaba.nacos.common.http.client.NacosAsyncRestTemplate; +import com.alibaba.nacos.common.http.client.NacosRestTemplate; +import com.alibaba.nacos.common.utils.ExceptionUtil; +import com.alibaba.nacos.common.utils.ThreadUtils; +import com.alibaba.nacos.config.server.utils.PropertyUtil; +import org.slf4j.Logger; +import org.slf4j.LoggerFactory; + +/** + * http client manager. + * + * @author mai.jh + */ +public final class HttpClientManager { + + private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientManager.class); + + /** + * Connection timeout and socket timeout with other servers. + */ + private static final int TIMEOUT = 500; + + private static final NacosRestTemplate NACOS_REST_TEMPLATE; + + private static final NacosAsyncRestTemplate NACOS_ASYNC_REST_TEMPLATE; + + static { + // build nacos rest template + NACOS_REST_TEMPLATE = HttpClientBeanHolder.getNacosRestTemplate(new ConfigHttpClientFactory(TIMEOUT, TIMEOUT)); + NACOS_ASYNC_REST_TEMPLATE = HttpClientBeanHolder.getNacosAsyncRestTemplate( + new ConfigHttpClientFactory(PropertyUtil.getNotifyConnectTimeout(), + PropertyUtil.getNotifySocketTimeout())); + + ThreadUtils.addShutdownHook(new Runnable() { + @Override + public void run() { + shutdown(); + } + }); + } + + public static NacosRestTemplate getNacosRestTemplate() { + return NACOS_REST_TEMPLATE; + } + + public static NacosAsyncRestTemplate getNacosAsyncRestTemplate() { + return NACOS_ASYNC_REST_TEMPLATE; + } + + private static void shutdown() { + LOGGER.warn("[ConfigServer-HttpClientManager] Start destroying NacosRestTemplate"); + try { + final String httpClientFactoryBeanName = ConfigHttpClientFactory.class.getName(); + HttpClientBeanHolder.shutdownNacostSyncRest(httpClientFactoryBeanName); + HttpClientBeanHolder.shutdownNacosAsyncRest(httpClientFactoryBeanName); + } catch (Exception ex) { + LOGGER.error("[ConfigServer-HttpClientManager] An exception occurred when the HTTP client was closed : {}", + ExceptionUtil.getStackTrace(ex)); + } + LOGGER.warn("[ConfigServer-HttpClientManager] Destruction of the end"); + } + + /** + * http client factory. + */ + private static class ConfigHttpClientFactory extends AbstractHttpClientFactory { + + private final int conTimeOutMillis; + + private final int readTimeOutMillis; + + public ConfigHttpClientFactory(int conTimeOutMillis, int readTimeOutMillis) { + this.conTimeOutMillis = conTimeOutMillis; + this.readTimeOutMillis = readTimeOutMillis; + } + + @Override + protected HttpClientConfig buildHttpClientConfig() { + return HttpClientConfig.builder().setConTimeOutMillis(conTimeOutMillis) + .setReadTimeOutMillis(readTimeOutMillis).build(); + } + + @Override + protected Logger assignLogger() { + return LOGGER; + } + } +} diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyService.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyService.java index adb9deef5ae..78cd0de14d4 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyService.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyService.java @@ -16,17 +16,15 @@ package com.alibaba.nacos.config.server.service.notify; -import com.alibaba.nacos.common.utils.IoUtils; +import com.alibaba.nacos.common.constant.HttpHeaderConsts; +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.CollectionUtils; import com.alibaba.nacos.config.server.manager.TaskManager; import com.alibaba.nacos.core.cluster.ServerMemberManager; -import org.apache.commons.lang3.StringUtils; import org.springframework.beans.factory.annotation.Autowired; -import javax.servlet.http.HttpServletResponse; -import java.io.IOException; -import java.net.HttpURLConnection; -import java.net.URL; -import java.util.Iterator; import java.util.List; /** @@ -53,65 +51,24 @@ protected NotifyService() { public static final String NOTIFY_HEADER_OP_HANDLE_IP = "opHandleIp"; + private TaskManager notifyTaskManager; + /** * Invoke http get request. * * @param url url * @param headers headers * @param encoding encoding - * @return {@link HttpResult} - * @throws IOException throw IOException + * @return {@link com.alibaba.nacos.common.model.RestResult} + * @throws Exception throw Exception */ @SuppressWarnings("checkstyle:AbbreviationAsWordInName") - public static HttpResult invokeURL(String url, List headers, String encoding) throws IOException { - HttpURLConnection conn = null; - try { - conn = (HttpURLConnection) new URL(url).openConnection(); - - conn.setConnectTimeout(TIMEOUT); - conn.setReadTimeout(TIMEOUT); - conn.setRequestMethod("GET"); - - if (null != headers && !StringUtils.isEmpty(encoding)) { - for (Iterator iter = headers.iterator(); iter.hasNext(); ) { - conn.addRequestProperty(iter.next(), iter.next()); - } - } - conn.addRequestProperty("Content-Type", "application/x-www-form-urlencoded;charset=" + encoding); - // establish TCP connection - conn.connect(); - // Send request internally - int respCode = conn.getResponseCode(); - String resp = null; - - if (HttpServletResponse.SC_OK == respCode) { - resp = IoUtils.toString(conn.getInputStream(), encoding); - } else { - resp = IoUtils.toString(conn.getErrorStream(), encoding); - } - return new HttpResult(respCode, resp); - } finally { - IoUtils.closeQuietly(conn); - } - } - - public static class HttpResult { - - public final int code; - - public String content; - - public HttpResult(int code, String content) { - this.code = code; - this.content = content; + public static RestResult invokeURL(String url, List headers, String encoding) throws Exception { + Header header = Header.newInstance(); + header.addParam(HttpHeaderConsts.ACCEPT_CHARSET, encoding); + if (CollectionUtils.isNotEmpty(headers)) { + header.addAll(headers); } + return HttpClientManager.getNacosRestTemplate().get(url, header, Query.EMPTY, String.class); } - - /** - * Connection timeout and socket timeout with other servers. - */ - static final int TIMEOUT = 500; - - private TaskManager notifyTaskManager; - } diff --git a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java index 7c35a02a9f8..215a20f4b6c 100755 --- a/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java +++ b/config/src/main/java/com/alibaba/nacos/config/server/service/notify/NotifyTaskProcessor.java @@ -16,17 +16,16 @@ package com.alibaba.nacos.config.server.service.notify; +import com.alibaba.nacos.common.model.RestResult; import com.alibaba.nacos.config.server.constant.Constants; import com.alibaba.nacos.config.server.manager.AbstractTask; import com.alibaba.nacos.config.server.manager.TaskProcessor; import com.alibaba.nacos.config.server.monitor.MetricsMonitor; -import com.alibaba.nacos.config.server.service.notify.NotifyService.HttpResult; import com.alibaba.nacos.config.server.service.trace.ConfigTraceService; import com.alibaba.nacos.core.cluster.Member; import com.alibaba.nacos.core.cluster.ServerMemberManager; import com.alibaba.nacos.core.utils.ApplicationUtils; import com.alibaba.nacos.core.utils.InetUtils; -import org.apache.http.HttpStatus; import org.slf4j.Logger; import org.slf4j.LoggerFactory; @@ -78,8 +77,8 @@ boolean notifyToDump(String dataId, String group, String tenant, long lastModifi String urlString = MessageFormat .format(URL_PATTERN, serverIp, ApplicationUtils.getContextPath(), dataId, group); - HttpResult result = NotifyService.invokeURL(urlString, headers, Constants.ENCODE); - if (result.code == HttpStatus.SC_OK) { + RestResult result = NotifyService.invokeURL(urlString, headers, Constants.ENCODE); + if (result.ok()) { ConfigTraceService.logNotifyEvent(dataId, group, tenant, null, lastModified, InetUtils.getSelfIp(), ConfigTraceService.NOTIFY_EVENT_OK, delayed, serverIp); @@ -89,7 +88,7 @@ boolean notifyToDump(String dataId, String group, String tenant, long lastModifi } else { MetricsMonitor.getConfigNotifyException().increment(); LOGGER.error("[notify-error] {}, {}, to {}, result {}", - new Object[] {dataId, group, serverIp, result.code}); + new Object[] {dataId, group, serverIp, result.getCode()}); ConfigTraceService.logNotifyEvent(dataId, group, tenant, null, lastModified, InetUtils.getSelfIp(), ConfigTraceService.NOTIFY_EVENT_ERROR, delayed, serverIp); return false; diff --git a/config/src/main/java/com/alibaba/nacos/config/server/utils/JSONUtils.java b/config/src/main/java/com/alibaba/nacos/config/server/utils/JSONUtils.java deleted file mode 100644 index 139933f3cda..00000000000 --- a/config/src/main/java/com/alibaba/nacos/config/server/utils/JSONUtils.java +++ /dev/null @@ -1,57 +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.config.server.utils; - -import com.fasterxml.jackson.core.type.TypeReference; -import com.fasterxml.jackson.databind.DeserializationFeature; -import com.fasterxml.jackson.databind.ObjectMapper; - -import java.io.IOException; -import java.io.InputStream; - - -/** - * Json util. - * - * @author Nacos - */ -@SuppressWarnings({"PMD.ClassNamingShouldBeCamelRule", "checkstyle:AbbreviationAsWordInName"}) -public class JSONUtils { - - static ObjectMapper mapper = new ObjectMapper(); - - static { - mapper.disable(DeserializationFeature.FAIL_ON_UNKNOWN_PROPERTIES); - } - - public static String serializeObject(Object o) throws IOException { - return mapper.writeValueAsString(o); - } - - public static Object deserializeObject(String s, Class clazz) throws IOException { - return mapper.readValue(s, clazz); - } - - public static T deserializeObject(String s, TypeReference typeReference) throws IOException { - return mapper.readValue(s, typeReference); - } - - public static T deserializeObject(InputStream src, TypeReference typeReference) throws IOException { - return mapper.readValue(src, typeReference); - } - -} diff --git a/test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplate_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplate_ITCase.java index 4039e94a3e5..2a431dd183c 100644 --- a/test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplate_ITCase.java +++ b/test/src/test/java/com/alibaba/nacos/test/common/NacosAsyncRestTemplate_ITCase.java @@ -40,7 +40,7 @@ import java.util.Map; /** - * NacosAsyncRestTemplate_ITCase + * NacosAsyncRestTemplate_ITCase. * * @author mai.jh */ diff --git a/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java b/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java index 801089b85e9..de1d71ee528 100644 --- a/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java +++ b/test/src/test/java/com/alibaba/nacos/test/common/NacosRestTemplate_ITCase.java @@ -18,20 +18,14 @@ import com.alibaba.nacos.Nacos; import com.alibaba.nacos.api.exception.NacosException; -import com.alibaba.nacos.client.config.http.ServerHttpAgent; import com.alibaba.nacos.common.http.HttpClientBeanHolder; import com.alibaba.nacos.common.http.HttpRestResult; import com.alibaba.nacos.common.http.client.NacosRestTemplate; 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.JacksonUtils; import com.alibaba.nacos.config.server.model.ConfigInfo4Beta; -import com.alibaba.nacos.config.server.utils.JSONUtils; -import com.alibaba.nacos.core.utils.GenericType; -import com.alibaba.nacos.test.smoke.nacosSmoke_ITCase; import com.fasterxml.jackson.core.type.TypeReference; -import org.apache.log4j.Logger; import org.junit.Assert; import org.junit.Before; import org.junit.FixMethodOrder; @@ -47,7 +41,7 @@ import java.util.Map; /** - * NacosRestTemplate_ITCase + * NacosRestTemplate_ITCase. * * @author mai.jh */