我想检查后端的健康状况,如果后端死了,我将停用这个后端。
我使用 ThreadPool 启动一个线程,每 10 秒使用 ip + 端口 ping 我的后端。
通过使用 Socket 类,我一开始不会关闭套接字。
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(domain, port);
try {
socket.connect(address, 3000);
if (socket.isConnected()) {
successCount++;
}
} catch (IOException e) {
e.printStackTrace();
}
然后我关闭套接字。
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(domain, port);
try {
socket.connect(address, 3000);
if (socket.isConnected()) {
successCount++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
try {
socket.close();
} catch (IOException e) {
e.printStackTrace();
}
}
我想找出这个条件在内存使用方面的区别。
我使用jconsole来显示内存的使用情况。
但是我发现如果我关闭套接字,内存的使用率会高于我不关闭它。
这是关于记忆的图片。我想知道为什么会这样。 在此处输入图像描述
private void backendHealthCheck() {
Map<String, Boolean> backendHealthMap = new ConcurrentHashMap<>();
List<ProxyBackendConfiguration> allBackends = gatewayBackendManager.getAllBackends();
for (ProxyBackendConfiguration backend : allBackends) {
String backendName = backend.getName();
Boolean backendStatus = gatewayBackendManager.getBackendStatus(backendName);
log.debug("[{}] 对应的后端状态为 [{}]", backendName, backendStatus);
backendHealthMap.put(backendName, backendStatus);
}
scheduledExecutorService.scheduleWithFixedDelay(
() -> {
log.info("Check the backend's healthy condition");
List<ProxyBackendConfiguration> backends = gatewayBackendManager.getAllBackends();
for (ProxyBackendConfiguration backend : backends) {
int successCount = 0;
String domain = backend.getProxyTo().substring(8, 36);
int port = Integer.parseInt(backend.getProxyTo().substring(37, 41));
String backendName = backend.getName();
for (int i = 0; i < 7; i++) {
Socket socket = new Socket();
InetSocketAddress address = new InetSocketAddress(domain, port);
try {
socket.connect(address, 3000);
if (socket.isConnected()) {
successCount++;
}
} catch (IOException e) {
e.printStackTrace();
}
if (successCount >= 2) {
// if the backend is active then break, else active this backend
// if this is not in map, get false active this backend
// if this backend in this map,and status is false,then active this backend
if (!backendHealthMap.getOrDefault(backendName, false)) {
gatewayBackendManager.activateBackend(backendName);
backendHealthMap.put(backendName, true);
}
break;
}
if (i == 6) {
// if this backend in map and the status is false, continue
// if this backend is not in map, get status is true,then deactive this backend
// if this backedn in map, and status is true,then deactive this backend
if (backendHealthMap.getOrDefault(backendName, true)) {
gatewayBackendManager.deactivateBackend(backendName);
backendHealthMap.put(backendName, false);
}
}
}
}
},
0,
10,
TimeUnit.SECONDS);
}