springboot自定义线程池配合@EnableAsync和@Async使用小例子

随便写点吧, 在springboot里自定义线程池配合@Async使用的小例子:

@Configuration
@EnableAsync
public class SyncConfiguration implements AsyncConfigurer {

    private static final Logger logger = LoggerFactory.getLogger(SyncConfiguration.class);

    @Bean(name = "asyncPoolTaskExecutor")
    public Executor executor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        //核心线程数
        executor.setCorePoolSize(10);
        //线程池维护的线程最大数量,只有在缓冲队列满了之后才会申请超过核心线程数量的线程
        executor.setMaxPoolSize(20);
        //缓存队列
        executor.setQueueCapacity(100);
        //允许的空闲时间,当超过了核心线程之外的线程在空闲时间到达之后会被销毁
        executor.setKeepAliveSeconds(60);
        //异步方法内部线程名字
        executor.setThreadNamePrefix("task-async-");
        /**
         * 到线程池的任务缓存队列已满并且线程池中的线程数到达了maxPoolSize,如果还有任务到来就会采取任务拒绝策略,
         * 通常有以下四种策略:
         * ThreadPoolExecutor.AbortPolicy:丢弃任务并抛出RejectedExecutionException异常
         * ThreadPoolExecutor.DiscardPolicy:丢弃任务,但不抛出异常
         * ThreadPoolExecutor.DiscardOldestPolicy:丢弃队列最前边的任务,然后重新尝试执行任务(重复此过程)
         * TreadPoolExecutor.CallerRunsPolicy:重试添加当前的任务,自动重复调用execute()方法,直到成功
         */
        executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
        //初始化
        executor.initialize();
        return executor;
    }

    @Override
    public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
        return (throwable, method, objects) -> {
            logger.error(throwable.getMessage());
        };
    }
}

专门写一个配置类来定义线程池, 当然也可以不实现AsyncConfigurer这个接口, 如果实现了可以在重写的这个方法里获取到异步线程在执行时抛出来的异常作为日志打印出来;也可以将异步执行的方法返回值定义为CompletableFuture<?>类型

如下例子:

//@Controller

public void exampleController() {
     //这里应该是使用注入的service对象来调用异步的方法
     CompletableFuture<String> future = exampleService();
     try {
         //get()方法是会阻塞主线程的
         future.get();
     } catch (Exception e) {
         //throw CustomizingGlobalException 
     }
 }


//@service

@Async(value = "asyncPoolTaskExecutor")
public CompletableFuture<String> exampleService() {
    //一些处理逻辑...
    String value = "假如这是执行完的String类型(也可以是别的类型)的结果";
    return CompletableFuture.completedFuture(value);

}

欢迎大家一起讨论, 如有更好的方法请不吝赐教

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值