使用 Spring Boot 的多个 REST 调用

Posted

技术标签:

【中文标题】使用 Spring Boot 的多个 REST 调用【英文标题】:Multiple REST Calls using Spring Boot 【发布时间】: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 中是否有内置功能或类似的东西可以用于这种情况。 【参考方案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/

【讨论】:

以上是关于使用 Spring Boot 的多个 REST 调用的主要内容,如果未能解决你的问题,请参考以下文章