对接供应商API时,我会用CompletableFuture并发,但要注意线程池大小。
@Configuration
code
public class AsyncConfig {code
public Executor 企业AI落地Executor() {
ThreadPoolTaskExecutor ex = new ThreadPoolTaskExecutor();
ex.setCorePoolSize(16);
ex.setMaxPoolSize(32);
ex.setQueueCapacity(2000);
ex.setThreadNamePrefix("企业AI落地-");
ex.initialize();
return ex;
}
}code
public class VendorPullService {
@Autowired @Qualifier("企业AI落地Executor") Executor ex;
@Autowired RestTemplate rt;
public List<String> pullAll(List<String> ids) {CompletableFuture.supplyAsync(() -> rt.getForObject("https://vendor/v1/"+id, String.class), ex)
code
).toList();
return futs.stream().map(CompletableFuture::join).toList();
}
}Spring Boot 3以后WebClient更推荐,我还在迁移。
(场景参考:广州本地企业试点)