最近,我们正在开发一个监控仪表板,我们想要ping几个第三方服务器,只是为了检查它们的可用性,或者我们想要调用健康检查。
我们正在对服务器进行一系列api调用,这些服务器的IP,用户名和密码被外部化为环境变量。
然后是我们的负载均衡器抛出HTTP 504(网关超时)的挑战,因为这些请求花了很多时间来返回结果。
因此,我们继续使用Callable和Future同时进行这些调用以减少所需的时间。
在开发多线程应用程序的传统方式中,我们创建线程并为其提供Runnable任务。Callable与Runnable非常相似,它有一个细微的区别,它可以返回结果或抛出异常,而Runnable的run方法的返回类型为void。
Runnable runnable = new Runnable() { @Override public void run() { // this can neither return the result nor throw an exception } }
|
但是,Callable可以返回任务的结果并且可以抛出异常。您也可以指定结果类型。为简单起见,我把它作为String,但只要call()方法返回它,它就可以是任何复杂的对象。Callable<String> callable = new Callable<String>() { @Override public String call() throws Exception { return "this can return output OR can throw Exception"; } };
|
既然您有Callable或任务,您需要能够运行该任务以获得输出。您可以使用ExecutorService使用它的submit()方法运行任务,或使用invokeAll()运行多个任务 ,您可以在其中提交可调用任务的集合。
现在是有趣的部分,submit()的返回类型是Future <T>,其中T是输出(String,如上例所示),invokeAll()的返回类型是List <Future <T >>
Future表示异步计算的结果。Java提供了检查计算是否完成,等待它完成或从中检索结果的方法。(它非常类似于javascript承诺,如果这使它易于理解)。因此,为了获得未来的结果,我们只需要调用get()就可以了
ExecutorService executorService = Executors.newFixedThreadPool(10); // callable from above code Future<String> future = executorService.submit(callable); String output = future.get();
|
下面是完整代码:
public class HealthCheckService {
private HttpHandler httpHandler; private Config config; private ExecutorService executor;
public HealthCheckService(HttpHandler httpHandler,Config config) { this.httpHandler = httpHandler; this.configuration = configuration; int size = config.servers.size(); this.executor = Executors.newFixedThreadPool(size); }
public List<HealthCheckResult> getHealthCheck() throws Exception { List<Callable<HealthCheck>> tasks = prepareTasks(config.uri); List<Future<HealthCheck>> futures = executor.invokeAll(tasks); List<HealthCheck> output = new ArrayList<>(); for (Future<HealthCheckResult> future: futures) { output.add(future.get()); } return output; }
private List<Callable<HealthCheck>> prepareTasks(String api) { List<Callable<HealthCheckResult>> tasks = new ArrayList(); for (String server: config.servers) { tasks.add(() -> httpHandler.getStatus(api)); } return tasks; } }
|
源码见:Github