ThreadPoolTaskExecutor以及通过注解实现异步任务

ThreadPoolTaskExecutor是Spring框架的线程池,实现方式如下:

 1 //声明一个name为asyncTaskExecutor的线程池bean到容器中
 2 @Bean("asyncTaskExecutor")
 3 public Executor getAsyncExecutor() {
 4     ThreadPoolTaskExecutor threadPoolExecutor = new ThreadPoolTaskExecutor();
 5     //核心线程数
 6     threadPoolExecutor.setCorePoolSize(ThreadPoolConfig.CORE_POOL_SIZE);
 7     //最大线程数量
 8     threadPoolExecutor.setMaxPoolSize(ThreadPoolConfig.MAX_POOL_SIZE);
 9     //等待队列
10     threadPoolExecutor.setQueueCapacity(ThreadPoolConfig.WORK_QUEUE);
11     //线程池名称RVCAsyncTaskPool
12     threadPoolExecutor.setThreadNamePrefix("RVCAsyncTaskPool-");
13     //空闲存活时间
14     threadPoolExecutor.setKeepAliveSeconds(ThreadPoolConfig.KEEP_ALIVE_TIME);
15     //拒绝策略
16     threadPoolExecutor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
17     //装饰器,本项目中主要应用于http请求,所以在自定义装饰器RvcAsyncTaskDecorator中,用于传递httpRequest的header信息
18     threadPoolExecutor.setTaskDecorator(new RvcAsyncTaskDecorator());
19     threadPoolExecutor.initialize();
20     return threadPoolExecutor;
21 }

TaskDecorator:执行回调方法的装饰器,主要应用于传递上下文,或者提供任务的监控/统计信息

RvcAsyncTaskDecorator装饰器为:

 1 public class RvcAsyncTaskDecorator implements TaskDecorator {
 2     @Override
 3     public Runnable decorate(Runnable runnable) {
 4         //headerMap为当前HttpRequest请求的header信息
 5         //RequestContextHolder.getRequestAttributes().getRequest();
 6         Map<String, String> headerMap = HttpHeaderUtils.shareHttpHeader();
 7         return () -> {
 8             try {
 9                 HttpHeaderUtils.setHeaderThreadLocal(headerMap);
10                 runnable.run();
11             } finally {
12                 HttpHeaderUtils.remove();
13             }
14         };
15     }
16 }

实现异步方法的注解的切面RvcAsyncAspect为:

 1 @Component
 2 @Aspect
 3 @RequiredArgsConstructor
 4 @Order(Ordered.HIGHEST_PRECEDENCE)
 5 public class RvcAsyncAspect {
 6     private final Executor asyncTaskExecutor;
 7 
 8     @Around("@annotation(rvc.core.annotation.RvcAsync)")
 9     public void doAround(ProceedingJoinPoint point) {
10         //runAsync无参数返回的异步执行,supplyAsync为有返回值的异步执行
11         CompletableFuture.runAsync(() -> {
12             try {
13                 this.proceed(point);
14             } catch (Exception ex) {
15                 //doSomething
16             }
17         }, asyncTaskExecutor);
18     }
19 
20     @SneakyThrows
21     private void proceed(ProceedingJoinPoint point) {
22         point.proceed();
23     }
24 }

注解RvcAsync为:

1 @Target(ElementType.METHOD)
2 @Retention(RetentionPolicy.RUNTIME)
3 @Documented
4 public @interface RvcAsync {
5 }

 

posted @ 2024-02-16 15:03  leviH  阅读(8)  评论(0编辑  收藏  举报