简体   繁体   English

使用 ResponseEntity 从另一个 API 中提取信息

[英]Using ResponseEntity to extract information from another API

I have 2 API lets call them API1 and API2我有 2 个 API,可以称它们为 API1 和 API2
API1 is a system API that extracts data from a database and returns a List of Strings as a result. API1 是一个系统 API,它从数据库中提取数据并作为结果返回一个字符串列表。
API2 extracts the information from API1 and returns the List of Strings as is. API2 从 API1 中提取信息并按原样返回字符串列表。

Now my question is if API1 is down how do I handle it.现在我的问题是,如果 API1 已关闭,我该如何处理。 I know I have to use a ResponseEntity to extract the HTTP status code but I am unable to do it.我知道我必须使用 ResponseEntity 来提取 HTTP 状态代码,但我无法做到。 Conside the code below as an example以下面的代码为例

API1 service API1服务

private static List<String> getData(int attribute1){
//A piece of code that extracts data from the database based on the attribute1 and store the information in a res object<br>
    return res;
}

API2 service API2服务

private static List<String> getData(int attribute1){
    String uri="localhost:9191/getData/"+attribute1;
    private RestTemplate restTemplate = new RestTemplate();
    List<String> res = restTemplate.getForObject(uri, List.class);
    return res;
}

Would I need to change my return type of API1 service functions我是否需要更改 API1 服务函数的返回类型
If so how would they look like如果是这样,他们会是什么样子
Irrespective of what happens in API1, API2 will change and how so to accomodate ResponseEntity不管 API1 中发生了什么,API2 都会发生变化以及如何适应 ResponseEntity
Any help would be much appreciated.任何帮助将非常感激。

In case your API1 is down or has any problems, you'll get an exception calling the "getForObject" method using RestTemplate.如果您的 API1 出现故障或有任何问题,您将收到使用 RestTemplate 调用“getForObject”方法的异常。 If you read the documentation , you'll see that this method throws a RestClientException , which means that if you want to handle any problem with API1 you need to try/catch the method and handle the exception accordingly with your needs.如果您阅读文档,您会看到此方法抛出RestClientException ,这意味着如果您想处理 API1 的任何问题,您需要尝试/捕获该方法并根据您的需要相应地处理异常。 So, you'll have something like this:所以,你会有这样的事情:

private static List getData(int attribute1) {

    String uri = "localhost:9191/getData/" + attribute1;

    private RestTemplate restTemplate = new RestTemplate();
    try {
        List res = restTemplate.getForObject(uri, List.class);
        return res;
    } catch(RestClientException rce) {
        // Here you'll handle the exception
    }
}

Also, note that the RestClientException has 3 direct subclasses: ResourceAccessException , RestClientResponseException and UnknownContentTypeException .另请注意,RestClientException 有 3 个直接子类: ResourceAccessExceptionRestClientResponseExceptionUnknownContentTypeException You could catch each one of these instead of cathing RestClientException, so you can handle them in different ways.您可以捕获其中的每一个而不是捕获 RestClientException,因此您可以以不同的方式处理它们。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM