如何从未来的结果中获得可致电通知

时间:2019-08-22 10:52:03

标签: java multithreading

我对服务节点执行ping操作,并检查其是否处于活动状态。我的课,对所有服务执行以下操作:

   public abstract class PingCallable implements Callable<ResponseEntity<String>> {


    @Override
    public ResponseEntity call() throws Exception {

        try {

            RestTemplate restTemplate = new RestTemplate();
            HttpHeaders headers = new HttpHeaders();
            HttpEntity<String> entity = new HttpEntity<>("", headers);

            return restTemplate.exchange(new URI(getPingUrl()), HttpMethod.GET, entity, String.class);

        } catch (Exception ex) {
            ex.printStackTrace();
            return new ResponseEntity("Exception occured while ping. Exception message = " + ExceptionUtil.getFullCauseMessage(ex), HttpStatus.INTERNAL_SERVER_ERROR);

        }
    }

    protected abstract String getPingUrl();

}

public class ServicePingCallable extends PingCallable {

    private Node node;

    public ServicePingCallable(Node node) {
        this.node = node;
    }

    @Override
    protected String getPingUrl() {
        return "//" + node.getIp() + "/api/" + node.getService().getServicePath() + "/pingService";
    }

   public Node getNode(){
        return this.node;
   }

}

ping服务节点的方法在这里:

 @Scheduled(fixedDelayString = "${config.ping.fixedDelay}")
public void pingServices() throws InterruptedException {

    List<Node> nodeList = serviceRepository.findAll();

    List<ServicePingCallable> callableList = new ArrayList<>(nodeList.size());

    ExecutorService executor = Executors.newFixedThreadPool(10);

    try {


        for (Node node : nodeList) {
            ServicePingCallable pingCallable = new ServicePingCallable(node);
            callableList.add(pingCallable);
        }

        List<Future<ResponseEntity<String>>> responses = executor.invokeAll(callableList, 10, TimeUnit.SECONDS);

                      for(Future<ResponseEntity<String>> response: responses){

              // here I should check response HttpStatus and response text and save node ping state.
// But how I can know here for which Node is response?    
//It whould be great to have such method: 
//ServicePingCallable  callable = (ServicePingCallable)response.getCallable();
//Node = callable.getNode();


            }
    } catch (Exception ex) {
       //catch and log here
    } finally {
        if (!executor.isShutdown()) {
            try {
                executor.shutdown();
            } catch (Exception ex1) {
            }
        }
    }

我可以将PingCallable的私有文件添加到ResponseEntity中,然后从call()的{​​{1}}返回,但是这种方法就像解决方法,并且不清楚。 我认为这是常见的任务,应该成为如何从未来结果中获取可赎回权的某种模式。如果您知道,请分享。

0 个答案:

没有答案