java - 在 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 并在那里处理额外的调用,但考虑到我需要检查每个调用的请求内容这一事实,直到当前方法结束才完成,它看起来像我们正在做很多双重工作。另一方面,在没有任何封装的情况下将解决方案应用到方法中会使后续维护变得更加困难(错误检查已经有点混乱了)。
我是不是想多了?在这里尝试以某种设计模式硬生生是错误的吗?
解决方案
推荐阅读
- css - 如何让 h1 和 h3 在弹性盒子的底部对齐?
- c - 分解为素数的意外问题 - C
- r - 有没有办法阻止 read.csv 对我的行进行排序?
- java - Files.getFileAttributeView(path, UserDefinedAttributeView.class) 在 Android 上返回 null
- imagemagick - 使用控制台中的 ZBar 进行 QR 码检测对于有效的 QR 码失败(来自摄像头的 ZBarCam 检测良好)
- amazon-web-services - 如何仅使用 aws codebuild 服务将 github 代码复制到 s3 存储桶?
- sql - 在 CTE 中使用 Order By 和 Left or right join
- go - 对子文件夹中的所有 go 模块运行测试
- c++ - 无法从类中删除动态数组
- python-3.x - 如何让我的类构造和其他函数在每个脚本运行时运行一次并保存用户输入?