springboot启动Async,并配置线程池

960 阅读1分钟

创建类MyAsyncConfig

继承AsyncConfigurer 可以更细致的配置,线程池,以及异常处理类。

@Configuration
@EnableAsync
@Log4j
public class MyAsyncConfig implements AsyncConfigurer {


    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setThreadNamePrefix("Anno-Executor");
        //最大线程数
        executor.setMaxPoolSize(10);
        //核心线程
        executor.setCorePoolSize(5);
        //队列大小
        executor.setQueueCapacity(999);
        executor.setWaitForTasksToCompleteOnShutdown(true);
        executor.setAwaitTerminationSeconds(60 * 15);
        executor.initialize();
        return executor;
    }


    //配置异常处理类
    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return new AsyncUncaughtExceptionHandler() {
            @Override
            public void handleUncaughtException(Throwable ex, Method method, Object... params) {
                log.info("Exception message - " + ex.getMessage());
                log.info("Method name - " + method.getName());
                for (Object param : params) {
                    log.info("Parameter value - " + param);
                }

            }
        };
    }
}

业务层AsyncService

方法上加上@Async 启动异步执行,打印线程id。如果打印的线程id为同一个,需要修改@Async(name=" ")

@Service
public class AsyncService {

    private static final Logger log = LoggerFactory.getLogger(AsyncService.class);

    /**
     * 最简单的异步调用,返回值为void
     */
    @Async
    public void asyncInvokeSimplest() {
        log.info("asyncSimplest{}",Thread.currentThread().getId());
    }

    /**
     * 带参数的异步调用 异步方法可以传入参数
     *
     * @param s
     */
    @Async
    public void asyncInvokeWithParameter(String s) {
        log.info("asyncInvokeWithParameter, parementer={}", s);
        log.info("{}",Thread.currentThread().getId());
        throw new IllegalArgumentException(s);
    }

    /**
     * 异常调用返回Future
     *
     * @param i
     * @return
     */
    @Async
    public Future<String> asyncInvokeReturnFuture(int i) {
        log.info("asyncInvokeReturnFuture, parementer={}", i);
        log.info("{}",Thread.currentThread().getId());
        Future<String> future;
        try {
            future = new AsyncResult<String>("success:" + i);
        } catch (Exception e) {
            future = new AsyncResult<String>("error");
        }
        return future;
    }


}

启动测试类

    @Autowired
    private AsyncService asyncService;

   @Test
    public void asynTest() throws ExecutionException, InterruptedException {
        asyncService.asyncInvokeSimplest();
        asyncService.asyncInvokeWithParameter("test");
        Future<String> future = asyncService.asyncInvokeReturnFuture(100);
        System.out.println(future.get());


    }