定义线程池 & 开启异步可用
在springboot中实现异步线程池非常简单,首先我们了解一下spring 中 AsyncConfigure 接口。
package org.springframework.scheduling.annotation;public interface AsyncConfigurer {//获取线程池@Nullabledefault Executor getAsyncExecutor() {return null;}//异步异常处理器@Nullabledefault AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {return null;}}
- getAsyncExecutor()返回一个自定义的异步线程池,这样开启异步,线程池会提供空闲线程来执行异步任务。
- getAsyncUncaughtExceptionHandler() 因为业务逻辑可能抛出异常,所以此方法是一个处理异常的处理器。
实例
配置类
@Configuration@EnableAsyncpublic class AsyncConfig implements AsyncConfigurer{@Overridepublic Executor getAsyncExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(30);executor.setQueueCapacity(1000);executor.initialize();return executor;}@Overridepublic AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {System.out.println("异常处理");return null;}}
- @EnableAsync 开启异步,这样就可以使用
@Async注解驱动了 - 实现
AsyncConfigurer接口,覆盖getAsyncExecutor()方法,这样就是实现了自定义线程池,当方法被@Async标注时,Spring就会通过这个线程池的空闲线程去运行该方法。使用方式
@Componentpublic class AsyncClass {@Asyncpublic void run() {for (int i=0;i<10;i++){if ( Thread.currentThread().isInterrupted() ) {System.out.println("i have interputed");}System.out.println("i:"+i);try {TimeUnit.SECONDS.sleep(1);} catch (InterruptedException e) {e.printStackTrace();}}}}
- 使用
@Async标识改方法是异步执行
