当前位置: 首页 > 知识库问答 >
问题:

CompletableFuture-运行多个rest调用抛出java。util。同时发生的完成例外

仇经武
2023-03-14

我有一个服务,使2调用另一个服务,然后组合的响应,并生成一个响应。

public HashMap<String,Double> getResp(String requestJson, double defaultScore, String anomalySelfInclUrl,String anomalySelfExclUrl){
        CompletableFuture<Double> f1 = getHelper(requestJson,anomalySelfInclUrl);
        CompletableFuture <Double>f2=  getHelper(requestJson,anomalySelfExclUrl);
        AnomalyResponse anomalyResponse =new AnomalyResponse();
        HashMap<String,Double> respMap= new HashMap<>();
        CompletableFuture.allOf(f1,f2)
                .thenRun(() -> {
                    try {
                        Double anomalySelfModelRes = f1.get();
                        Double anomalyExclModelRes = f2.get();
                        respMap.put(Constants.selfInc,anomalySelfModelRes);
                        respMap.put(Constants.selfExcl,anomalyExclModelRes);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }).join();
        return respMap;
    }

public CompletableFuture<Double> getHelper(String requestJson, String url)  {
        return CompletableFuture.supplyAsync(() -> {
            HttpHeaders headers = new HttpHeaders();
            headers.setContentType(MediaType.APPLICATION_JSON);
            HttpEntity<String> entity = new HttpEntity<>(requestJson, headers);
            String resp =restTemplate.postForObject(url, entity, String.class);
            JsonObject json = new JsonParser().parse(resp).getAsJsonObject();
            return json.get("score").getAsDouble();
        });

    }

在getResp方法中,我使用可完成的未来来创建2个帖子调用(通过getHelper方法)。一旦两个帖子调用完成,我将它们添加到HashMap并返回。但是我在postForObject()方法中得到以下错误。

org.jboss.resteasy.spi.UnhandledException: java.util.concurrent.CompletionException

错误似乎发生了,因为被调用的服务没有收到发布的json数据和标头(包装在HttpEntity中)。这怎么会发生呢?此问题不会在顺序调用期间出现。

共有1个答案

贺立果
2023-03-14

如果在completable future内执行该方法时出现异常,它将抛出completion exception。

假设您从API中获得401

您可以从objOfCompletionException获得实际响应。getCause()方法调用。它将包含实际发生异常的所有细节。

 类似资料: