Neste post mostrarei como executar um método de forma assíncrona com Spring Boot, para isso criei um projeto que exemplifica o uso deste recurso de maneira bem simples.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.matheuspcarvalho.taskexecutordemonstracao; | |
| import org.springframework.context.annotation.Bean; | |
| import org.springframework.context.annotation.ComponentScan; | |
| import org.springframework.context.annotation.Configuration; | |
| import org.springframework.scheduling.annotation.EnableAsync; | |
| import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor; | |
| @Configuration | |
| @ComponentScan("com.matheuspcarvalho.taskexecutordemonstracao") | |
| @EnableAsync | |
| public class AsyncConfiguration { | |
| @Bean | |
| public ThreadPoolTaskExecutor taskExecutor() { | |
| ThreadPoolTaskExecutor pool = new ThreadPoolTaskExecutor(); | |
| pool.setCorePoolSize(5); | |
| pool.setMaxPoolSize(10); | |
| pool.setWaitForTasksToCompleteOnShutdown(true); | |
| return pool; | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.matheuspcarvalho.taskexecutordemonstracao; | |
| import org.springframework.scheduling.annotation.Async; | |
| import org.springframework.stereotype.Service; | |
| @Service | |
| public class AsyncService { | |
| @Async | |
| public void hello() throws InterruptedException { | |
| Thread.sleep(10000); | |
| System.out.println("Hello Async!"); | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| package com.matheuspcarvalho.taskexecutordemonstracao; | |
| import org.springframework.beans.factory.annotation.Autowired; | |
| import org.springframework.web.bind.annotation.GetMapping; | |
| import org.springframework.web.bind.annotation.RestController; | |
| @RestController(value = "hello") | |
| public class HelloAsyncController { | |
| @Autowired | |
| private AsyncService helloService; | |
| @GetMapping | |
| public String hello() { | |
| String mensagemRetorno = "Sucesso!"; | |
| try { | |
| helloService.hello(); | |
| } catch (InterruptedException e) { | |
| mensagemRetorno = "Erro."; | |
| } | |
| return mensagemRetorno; | |
| } | |
| } |
Na classe AsyncConfiguration criamos um bean que configura o pool de threads.
Já na classe AsyncService uso a anotação @Async para dizer ao Spring que o método hello() deve ser executado de forma assíncrona. Para simular um possível processamento que envolve um maior tempo, usei o Thread.Sleep com 10 segundos de duração.
Finalmente temos o Controller para testarmos o resultado, que deve ser a visualização da mensagem de sucesso antes da execução do método hello().
Espero ajudar alguém com este post! 🙂
Salvou minha vida!! vlw
CurtirCurtido por 1 pessoa
Obrigado Matheus! Bastante objetivo!
CurtirCurtido por 1 pessoa
Muito bom mano!
Simples e objetivo.
CurtirCurtido por 1 pessoa