Spring supports asynchronus processing using @Async annotaiton.
Enable Async Processing To enable Scheduling annotation, add @EnableAsync to one of your @Configuration
class.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @Configuration @EnableAsync public class AsyncConfig { @Bean(name = "asyncExecutor") public Executor asyncExecutor () { ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor (); executor.setCorePoolSize(3 ); executor.setMaxPoolSize(3 ); executor.setQueueCapacity(100 ); executor.setThreadNamePrefix("AsynchThread-" ); executor.initialize(); return executor; } }
This class also create a customized Executor
bean. If you don’t create a Executor
bean. Spring by default will create a SimpleAsyncTaskExecutor bean.
@Async Annotation @Async tells Spring that the method is asynchronous and should run on a separate thread.
1 2 3 4 5 6 7 8 @Service @Slf4j public class SendMessageService { @Async( "asyncExecutor") public void sendMessage () { log.info(Thread.currentThread().getName() + " - sending message...." ); } }
We can invoke the method to demonstrate it is executed asynchronously. The folowing controller calls the async method in its sendMessage() method.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 @RestController @RequestMapping("/greeting") @Slf4j public class MyController { @Autowired SendMessageService sendMessageService; @RequestMapping(value = "/sendMessage", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE) public ResponseEntity<String> sendMessage () { sendMessageService.sendMessage(); return ResponseEntity.status(HttpStatus.OK).body("Success" ); } }
To test the method, we can invoke http://localhost:8080/greeting/sendMessage multiple times. We will see similar log output in the console. From the log, we know the method runs on asynchronous threads.
1 2 3 4 AsynchThread-1 - sending message.... AsynchThread-2 - sending message.... AsynchThread-3 - sending message.... AsynchThread-1 - sending message....
Project files: https://github.com/xinghua24/SpringBootExamples/tree/master/async
Reference