springboot启动Async,并配置线程池

本文详细介绍了如何在Spring Boot中配置并使用异步任务,包括创建自定义的`AsyncConfigurer`实现类,配置线程池,以及设置异常处理。示例展示了在业务层如何使用`@Async`注解进行异步方法调用,并提供了测试用例。通过这样的配置,可以灵活地管理异步任务的执行和异常处理。
摘要由CSDN通过智能技术生成

创建类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());


    }

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值