首页 > 解决方案 > 在 Spring 中编写一个灵活且干净的方法来处理多个 REST API 调用

问题描述

为了解决这个问题,让我们假设我们有一个下游服务,我们需要调用它来获取一些信息。我们设置了一个 API 端点并调用另一个方法来保存我们的业务逻辑并发出 HTTP 请求。根据发送到此方法的某些参数,我们可能必须对同一个端点进行多次调用,具体取决于它返回的内容。该方法当前设置如下:

public HttpEntity<String> getInfo(//parameters) {
    
    //setup HTTP headers etc.
    HttpEntity response = restTemplate.exchange(//stuff here);

    //based off of on the parameters given to this method, we will know whether or not we need to make additional calls
    //if we DO need to make additional calls, we will also need to inspect the response for information
    //this is difficult, because as you see below, this method doesn't start to procces the response until after error checking
    
    //do all error checking ie. checking for no data and other HTTP errors
    
    OurDataClass dataClass = objectmapper.writeValueasString(response.getBody());
    //do things to dataClass
    return new HttpEntity<String>(//dataClass and headers);

鉴于此方法的当前结构,我不知道如何将其转化为更具可扩展性和可维护性的东西。我的第一直觉是封装 restTemplate 并在那里处理额外的调用,但考虑到我需要检查每个调用的请求内容这一事实,直到当前方法结束才完成,它看起来像我们正在做很多双重工作。另一方面,在没有任何封装的情况下将解决方案应用到方法中会使后续维护变得更加困难(错误检查已经有点混乱了)。

我是不是想多了?在这里尝试以某种设计模式硬生生是错误的吗?

标签: javaspringrestdesign-patterns

解决方案


推荐阅读