如何在首个CompletableFuture未匹配时链式调用第二个独立实例?
整合匹配逻辑的解决方案
你可以通过CompletionStage的handle和thenCompose方法实现链式调用,先尝试第一个匹配器,失败后再调用第二个,整合后的代码如下:
private CompletionStage<Void> example(final Resource resource) { return firstMatcher.match(resource) // 处理第一个匹配的结果(包括异常情况) .handle((optMatch, throwable) -> { if (throwable != null || !optMatch.isPresent()) { LOGGER.debug("resource doesn't match first matcher"); return Optional.empty(); } LOGGER.debug("resource matches first matcher"); // 执行第一个匹配成功后的业务逻辑 // DONE return optMatch; }) // 根据第一个匹配的结果决定是否调用第二个匹配器 .thenCompose(optFirstMatch -> { if (optFirstMatch.isPresent()) { // 第一个匹配成功,直接返回已完成的Stage return CompletableFuture.completedFuture(null); } // 第一个匹配失败,执行第二个匹配逻辑 return secondMatcher.match(resource) .whenComplete((optSecondMatch, throwable) -> { if (throwable != null || !optSecondMatch.isPresent()) { LOGGER.debug("resource doesn't match second matcher"); } }) .thenAccept(optSecondMatch -> optSecondMatch.ifPresent(match -> { LOGGER.debug("resource matches second matcher"); // 执行第二个匹配成功后的业务逻辑 // DONE })); }); }
关键逻辑说明
handle方法:同时处理正常返回结果和异常情况,统一判断第一个匹配是否成功。如果失败,返回空Optional;如果成功,处理业务逻辑并保留匹配结果。thenCompose方法:用于连接后续逻辑。如果第一个匹配成功,直接返回已完成的CompletionStage结束流程;如果失败,则启动第二个匹配器的调用链。
内容的提问来源于stack exchange,提问作者Robert O'Neal
相关产品推荐
相关产品推荐

