异步注解相关
# 异步注解 Async
# 1、启动类开启异步线程
启动类上添加注解:@EnableAsync
# 2、配置线程池
示例:
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import java.util.concurrent.*;
@Configuration
@EnableAsync
public class AsyncConfig implements AsyncConfigurer {
@Bean(name = "customExecutor")
public Executor customExecutor() {
// 创建自定义线程池
int corePoolSize = 10; // 核心线程数
int maxPoolSize = 50; // 最大线程数
long keepAliveTime = 60L; // 非核心线程空闲存活时间
TimeUnit unit = TimeUnit.SECONDS; // 时间单位
BlockingQueue<Runnable> workQueue = new LinkedBlockingQueue<>(); // 工作队列
ThreadPoolExecutor executor = new ThreadPoolExecutor(
corePoolSize,
maxPoolSize,
keepAliveTime,
unit,
workQueue
);
// 允许核心线程超时
executor.allowCoreThreadTimeOut(true);
// 设置线程工厂
executor.setThreadFactory(new ThreadFactoryBuilder()
.setNameFormat("custom-async-pool-%d") // 线程名称格式
.build());
// 设置拒绝策略
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
return executor;
}
@Override
public Executor getAsyncExecutor() {
// 返回自定义线程池
return customExecutor();
}
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
// 设置异步执行时的异常处理器
return new SimpleAsyncUncaughtExceptionHandler();
}
public static class SimpleAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(Throwable ex, Method method, Object... params) {
System.err.println("Unhandled exception in " + method.getName() + " with parameters " + Arrays.deepToString(params));
ex.printStackTrace();
}
}
}
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
在这个配置类中,我们完成了以下内容:
- 通过
@Configuration
注解标注这个类是一个配置类。 - 通过
@EnableAsync
注解开启异步支持。 - 实现
AsyncConfigurer
接口,以自定义异步执行器和异常处理器。 - 创建了一个
ThreadPoolExecutor
作为自定义线程池,配置了核心线程数、最大线程数、空闲存活时间、工作队列等参数。 - 使用
ThreadFactoryBuilder
创建了一个命名的线程工厂。 - 设置了拒绝策略为
CallerRunsPolicy
,这意味着如果线程池达到饱和状态,任务将由调用者线程执行。 - 实现了自定义的异常处理器
SimpleAsyncUncaughtExceptionHandler
,用于处理异步方法执行中的未捕获异常。
# 3、方法体上添加异步注解
示例:
@Async
public void test() {
}
1
2
3
4
2
3
4
注意事项:
- 在内部类之间的方法调用,此注解无效,不会有异步线程
- 需要外部的类来调用这个异步方法才会开启异步线程
# 学习参考
上次更新: 2024/9/8 21:24:17