【问题标题】:Multiple REST Calls using Spring Boot使用 Spring Boot 的多个 REST 调用
【发布时间】:2022-01-07 17:44:57
【问题描述】:

我正在尝试使用 Spring Boot 对 API 进行 500 多次 REST 调用 (POST)。目前我正在使用thread pool 使用callable - executor service,因为我也需要来自POST 调用的响应。在 Spring Boot 中是否有更有效的方法来执行此操作? 编辑 - 这是一个 IO 密集型任务

【问题讨论】:

  • “在 Spring Boot 中有更有效的方法吗?” - 您想在处理器时间、内存消耗或其他方面提高效率吗?
  • 是的,关于处理器时间,内存使用。我想知道 Spring Boot 中是否有内置功能或类似的东西可以用于这种情况。

标签: java spring spring-boot threadpool


【解决方案1】:

您可以简单地使用 WebClient,因为它在设计上是非阻塞的。

参见例如:https://newbedev.com/springboot-how-to-use-webclient-instead-of-resttemplate-for-performing-non-blocking-and-asynchronous-calls 但是网络上还有很多其他资源。

但是...如果您使用的是 RestTemplate:

@Service
public class AsyncService {

    private final RestTemplate restTemplate;

    public AsyncService(RestTemplate restTemplate) {
        this.restTemplate = restTemplate;
    }

    @Async
    public CompletableFuture<ResponseDto[]> callAsync(RequestDto requestDto) {
        ResponseDto[] responseDtos = restTemplate.postForObject("someUrl", requestDto, ResponseDto[].class);
        
        return CompletableFuture.completedFuture(responseDtos);
    }
}

然后,您可以使用标准 Java Future 机制简单地循环来自任何适合您的上下文的位置的所有请求。

只需确保将@EnableAsync 添加到您的应用程序中

更详细的教程可以在这里找到:https://spring.io/guides/gs/async-method/

【讨论】:

    猜你喜欢
    • 2023-03-25
    • 2020-03-15
    • 1970-01-01
    • 2020-09-12
    • 2017-04-30
    • 2017-03-19
    • 2018-10-06
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多