How to asynchronously execute this method? I read on the Internet and it says that by default Spring is not asynchronous. But I noticed a strange feature: when testing this endpoint using Postman with 100 virtual threads, the test result shows that it processes 3.5 requests per second. But if I remove CompletableFuture and the @Async annotation, then the endpoint while testing processes 27 requests per second. But if Spring really wasn’t asynchronous, then on my CPU with 12 threads, the maximum processing speed would be 6 requests per second (according to a delay of 2 seconds).
I’m not good at asynchrony in Spring, could you give me a code example when using asynchrony would be useful and how to simply configurate it?
endpoint:
@Async
@GetMapping("/async")
public CompletableFuture<String> testAsync() {
return CompletableFuture.supplyAsync(() -> {
try {
Thread.sleep(2000);
} catch (InterruptedException e) {
Thread.currentThread().interrupt();
}
return "Result of long operation";
});
}
I also added @EnableAsync annotation and Executor method in Spring Boot Config class:
@SpringBootApplication
@EnableAsync
public class TestBootApplication implements AsyncConfigurer {
public static void main(String[] args) {
SpringApplication.run(TestBootApplication.class, args);
}
@Override
public Executor getAsyncExecutor() {
return Executors.newCachedThreadPool();
}
}