我正在尝试创建异步REST API。每次呼叫都会启动服务方法,该方法需要2秒钟才能完成。我想同时进行20次调用,并在不同的线程上启动所有这些方法,这样我的控制器就不会被阻塞,我可以在大约2秒钟内获得所有响应。
我尝试将@Asnyc批注添加到Controller和服务中,但是在给CompletableFuture作为响应之后,它们给了我空的响应,我得到了正确的响应,但是现在它不是异步的,我需要等待大约40秒回应。
@RestController
public class BasicController{
@Autowired
private BasicService basicService;
@Async("asyncExecutor")
@GetMapping("/basic/{owner}/{path}")
public CompletableFuture<InfoDTO>getGitApiInfo(@PathVariable("owner") String owner,
@PathVariable("path") String path) throws InterruptedException {
return basicService.getRepositoryInfo(owner, path);
}
}
@Service
public class BasicService{
@Async("asyncExecutor")
public CompletableFuture<InfoDTO> getRepositoryInfo(String owner, String repoName) throws InterruptedException {
Thread.sleep(2000);
return CompletableFuture.completedFuture(new InfoDTO(owner, repoName);
}
}
@EnableAsync
@Configuration
public class ServicesConfig {
@Bean(name = "asyncExecutor")
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(8);
executor.setMaxPoolSize(20);
executor.setQueueCapacity(500);
executor.setWaitForTasksToCompleteOnShutdown(true);
executor.setThreadNamePrefix("Async-");
executor.initialize();
return executor;
}
}
我希望使用邮递员赛跑者在2-3秒内从该控制器获得20个响应。