我正在从事一个项目,其中我有三个数据中心 -DC1
和.DC2
DC3
我DC1
有两台机器(machineA and machineB)
,DC2
我有两台机器(machineC and machineD)
,DC3
我又有两台机器(machineE and machineF)
。
每个数据中心中的每台机器 URL 都是这样的,它返回字符串作为响应 -
http://machineName:8080/textbeat
对于 DC1-
http://machineA:8080/textbeat
http://machineB:8080/textbeat
对于 DC2-
http://machineC:8080/textbeat
http://machineD:8080/textbeat
DC3-
http://machineE:8080/textbeat
http://machineF:8080/textbeat
这是我在点击任何特定机器的 url 后通常看到的响应字符串 -
state: READY server_uptime: 12462125 data_syncs: 29
问题陈述:-
现在我需要迭代每个数据中心中的所有机器并执行 URL,然后从中提取data_syncs
。这必须每 1 分钟完成一次。
现在如果machineA
data_syncs
连续 5 分钟始终为零,那么我想打印DC1
and machineA
。machineB 和其他数据中心也是如此。
我在想的逻辑——
- 从每个数据中心 ping 每台机器,
data_syncs
如果值为零,则提取该值,将计数器加一, - 然后在一分钟后重试,如果该值仍然为零,则再次将相同的计数器加一。
- 如果计数器达到 5(因为它是 5 分钟)并且它仍然连续为零,那么我会在我的地图中添加这台机器和数据中心的名称。
- 但是假设在连续三次尝试中它为零,而在第四次尝试中它变为非零,那么我的计数器将在数据中心中的那台机器上重置为零,并为那台机器再次启动该过程。
下面是我的地图,如果数据中心及其机器满足上述条件,我将在其中放置它们 -
final Map<String, List<String>> holder = new LinkedHashMap<String, List<String>>();
这里的键是数据中心名称,值是满足条件的数据中心的机器列表。
下面是我想出的解决上述问题的代码,但它不像我猜想的那样工作。counter
我猜这不是我想要的所有机器都是一样的。
public class MachineTest {
private static int counter = 0;
private final static ScheduledExecutorService scheduler = Executors.newScheduledThreadPool(2);
public static void main(String[] args) {
final ScheduledFuture<?> taskUtility = scheduler.scheduleAtFixedRate(new Runnable() {
public void run() {
try {
generalUtility();
} catch (Exception ex) {
// log an exception
}
}
}, 0, 1L, TimeUnit.MINUTES);
}
protected static void generalUtility() {
try {
final Map<String, List<String>> holder = new LinkedHashMap<String, List<String>>();
List<String> datacenters = Arrays.asList("DC1", "DC2", "DC3");
for (String datacenter : datacenters) {
LinkedList<String> machines = new LinkedList<String>();
List<String> childrenInEachDatacenter = getMachinesInEachDatacenter(datacenter);
for (String hosts : childrenInEachDatacenter) {
String host_name = hosts;
String url = "http://" + host_name + ":8080/textbeat";
MachineMetrics metrics = GeneralUtilities.getMetricsOfMachine(host_name, url); // execute the url and populate the MachineMetrics object
if (metrics.getDataSyncs().equalsIgnoreCase("0")) {
counter++;
if (counter == 5) {
machines.add(hosts);
}
}
}
if(!machines.isEmpty()) {
holder.put(datacenter, machines);
}
}
if (!holder.isEmpty()) {
// log the datacenter and its machine as our criteria is met
System.out.println(holder);
}
} catch (Exception e) {
e.printStackTrace();
}
}
// Below method will return list of machines given the name of datacenter
private static List<String> getMachinesInEachDatacenter(String datacenter) {
// this will return list of machines for a given datacenter
}
}
这是我的MachineMetrics
课-
public class MachineMetrics {
private String machineName;
private String dataSyncs;
// getters and setters
}
这是否可以使用 ScheduledExecutorService 来完成,因为这不是一次性过程?必须反复进行
基本上对于每台机器,如果连续data_syncs
一段时间为 0,那么我需要记录该数据中心及其机器。5 minutes