-
Notifications
You must be signed in to change notification settings - Fork 193
Expand file tree
/
Copy pathWebSocketWatchDog.java
More file actions
63 lines (45 loc) · 1.98 KB
/
WebSocketWatchDog.java
File metadata and controls
63 lines (45 loc) · 1.98 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
package com.huobi.utils;
import java.util.Map;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.CopyOnWriteArrayList;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import com.huobi.constant.enums.ConnectionStateEnum;
public class WebSocketWatchDog {
public static final long RECEIVE_LIMIT_TS = 60_000;
public static final int DELAY_ON_FAILURE = 15;
private static final Map<Long,WebSocketConnection> TIME_HELPER = new ConcurrentHashMap<>();
private static final Logger log = LoggerFactory.getLogger(WebSocketWatchDog.class);
static {
long t = 1_000;
ScheduledExecutorService exec = Executors.newScheduledThreadPool(1);
exec.scheduleAtFixedRate(() -> {
TIME_HELPER.entrySet().forEach(entry -> {
WebSocketConnection connection = entry.getValue();
if (connection.getState() == ConnectionStateEnum.CONNECTED) {
// Check response
long ts = System.currentTimeMillis() - connection.getLastReceivedTime();
if (ts > RECEIVE_LIMIT_TS) {
log.warn("[Sub][" + connection.getConnectionId() + "] No response from server");
connection.reConnect(DELAY_ON_FAILURE);
}
} else if (connection.getState() == ConnectionStateEnum.DELAY_CONNECT) {
connection.reConnect();
} else if (connection.getState() == ConnectionStateEnum.CLOSED_ON_ERROR) {
connection.reConnect(DELAY_ON_FAILURE);
}
});
}, t, t, TimeUnit.MILLISECONDS);
Runtime.getRuntime().addShutdownHook(new Thread(exec::shutdown));
}
private WebSocketWatchDog() {}
public static void onConnectionCreated(WebSocketConnection connection) {
TIME_HELPER.put(connection.getConnectionId(), connection);
}
public static void onClosedNormally(WebSocketConnection connection) {
TIME_HELPER.remove(connection.getConnectionId());
}
}