Skip to content

Commit

Permalink
for alibaba#3832, add common http client shutdown method. (alibaba#4150)
Browse files Browse the repository at this point in the history
  • Loading branch information
Maijh97 authored Nov 6, 2020
1 parent 5385095 commit 51fa1c0
Showing 1 changed file with 33 additions and 0 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -18,10 +18,14 @@

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 org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.atomic.AtomicBoolean;

/**
* Create a rest template to ensure that each custom client config and rest template are in one-to-one correspondence.
Expand All @@ -30,11 +34,24 @@
*/
public final class HttpClientBeanHolder {

private static final Logger LOGGER = LoggerFactory.getLogger(HttpClientBeanHolder.class);

private static final Map<String, NacosRestTemplate> SINGLETON_REST = new HashMap<String, NacosRestTemplate>(10);

private static final Map<String, NacosAsyncRestTemplate> SINGLETON_ASYNC_REST = new HashMap<String, NacosAsyncRestTemplate>(
10);

private static final AtomicBoolean ALREADY_SHUTDOWN = new AtomicBoolean(false);

static {
ThreadUtils.addShutdownHook(new Runnable() {
@Override
public void run() {
shutdown();
}
});
}

public static NacosRestTemplate getNacosRestTemplate(Logger logger) {
return getNacosRestTemplate(new DefaultHttpClientFactory(logger));
}
Expand Down Expand Up @@ -81,6 +98,22 @@ public static NacosAsyncRestTemplate getNacosAsyncRestTemplate(HttpClientFactory
return nacosAsyncRestTemplate;
}

/**
* Shutdown common http client.
*/
private static void shutdown() {
if (!ALREADY_SHUTDOWN.compareAndSet(false, true)) {
return;
}
LOGGER.warn("[HttpClientBeanHolder] Start destroying common HttpClient");
try {
shutdown(DefaultHttpClientFactory.class.getName());
} catch (Exception ex) {
LOGGER.error("An exception occurred when the common HTTP client was closed : {}", ExceptionUtil.getStackTrace(ex));
}
LOGGER.warn("[HttpClientBeanHolder] Destruction of the end");
}

/**
* Shutdown http client holder and close remove template.
*
Expand Down

0 comments on commit 51fa1c0

Please sign in to comment.