SpringBoot原生异步调用步骤
- 在启动类或者是线程池配置类上添加@EnableAsync注解,表示启用异步处理
- 在Configuration配置类里将线程池添加到IOC容器里(一般使用@Bean和@Qualifier这两个注解)
- 在需要使用线程池异步调用的方法上添加@Aysnc注解,value值给之前在配置类里面定义的该Bean的名字.
案例:
(1)首先创建一个空的SpringBoot项目
(2)然后配置类如下
/**
* <p>
* description
* </p>
*
* @Author HONG.SHAO@hand-china.com 2020/8/27 15:50
**/
@Configuration
@EnableAsync
public class JustConfig {
@Bean
@Qualifier("justAysncTaskExecutor")
public AsyncTaskExecutor asyncTaskExecutor(){
ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();
threadPoolExecutor.setThreadGroupName("just-executor");
threadPoolExecutor.setCorePoolSize(2);
threadPoolExecutor.setMaxPoolSize(8);
threadPoolExecutor.setQueueCapacity(12);
return threadPoolExecutor;
}
}
(3)最后编写需要异步执行的方法
@Service
public class AsyncService {
Logger logger = LoggerFactory.getLogger(AsyncService.class);
@Async(value = "justAysncTaskExecutor")
public void asyncTask(){
for (int i = 0; i < 10; i++) {
try {
Thread.sleep(1000);
} catch (InterruptedException e) {
e.printStackTrace();
}
logger.info(Thread.currentThread().getName()+"----正在处理----"+i);
}
}
}
(4)最后就是测试
@SpringBootTest
class AsyncmultithreadApplicationTests {
@Autowired
private AsyncService asyncService;
@Test
void contextLoads() {
asyncService.asyncTask();
asyncService.asyncTask();
asyncService.asyncTask();
System.out.println("--------主线程执行完毕");
}
}
(5)运行结果
可以看出,当主线程执行退出后,线程池里面的线程并没有随着主线程结束而终止,当线程池中线程执行完毕后线程池会自行shutdown,不需要我们开发人员去处理。