Async
For Spring async to work, we have to @EnableAsync
.
@SpringBootApplication
@EnableAsync
public class Application {
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
And then we can use @Async
to denote method that is async to run in a separate thread.
The method that is async needs to have a Future<>
return or void
@Slf4j
@Service
public class TaskService {
@Async
public Future<String> getResult() {
return CompletableFuture.completedFuture("hi");
}
}
@RestController
public class MyController {
@RequestMapping(value = "/asynctest", method = RequestMethod.GET)
public String getValue() throws ExecutionException, InterruptedException {
return taskService.getResult().get();
}
}