Let's create a service that keeps on pinging multiple services and give their status like live,down and so on..
public class PingService {
private static String url1 = "http://localhost:8082";
private static String url2 = "http://localhost:8083";
private static String url3 = "http://localhost:8084";
public List<ServerStatusVO> collectStatus() {
List<ServiceInfo> serviceList = getRunningServiceList();
List<ServerStatusVO> statusList = new ArrayList<>();
ScheduledExecutorService execService = Executors.newScheduledThreadPool(3);
List<Callable<ServerStatusVO>> callableList = new ArrayList<Callable<ServerStatusVO>>();
for (ServiceInfo service : serviceList) {
callableList.add(new PingHost(service.getId(), service.getUrl()));
}
try {
List<Future<ServerStatusVO>> resultFuture = execService.invokeAll(callableList);
for (Future<ServerStatusVO> future : resultFuture) {
try {
statusList.add(future.get());
} catch (ExecutionException e) {
e.printStackTrace();
}
}
} catch (InterruptedException e1) {
e1.printStackTrace();
}
execService.shutdown();
try {
if (execService.awaitTermination(10, TimeUnit.SECONDS)) {
System.out.println("All threads done with their jobs");
}
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Final Sum : ");
return statusList;
}
class PingHost implements Callable<ServerStatusVO> {
RestTemplate restTemplate = new RestTemplate();
String id;
String host;
public PingHost(String id, String host) {
this.host = host;
this.id = id;
}
@Override
public ServerStatusVO call() throws Exception {
ServerStatusVO serverStatusVO = new ServerStatusVO();
serverStatusVO.setUrl(host);
serverStatusVO.setId(id);
try {
String widget = restTemplate.getForObject(host, String.class);
if (StringUtils.isBlank(widget)) {
serverStatusVO.setStatus("success");
System.out.println("success......");
} else {
serverStatusVO.setStatus("success");
}
} catch (Exception e) {
serverStatusVO.setStatus("failure");
System.out.println("failure......" + e);
}
return serverStatusVO;
}
}
private List<ServiceInfo> getRunningServiceList() {
List<String> hostList = new ArrayList<>();
hostList.add(url1);
hostList.add(url2);
hostList.add(url3);
List<ServiceInfo> serviceList = new ArrayList<>();
int i = 1;
for (String service : hostList) {
serviceList.add(new ServiceInfo(i + "", service));
i++;
}
return serviceList;
}
}