当前位置:网站首页>@Async注解的作用以及如何实现异步监听机制
@Async注解的作用以及如何实现异步监听机制
2022-08-04 23:08:00 【步尔斯特】
使用@Async标注在方法上,可以使该方法异步的调用执行。而所有异步方法的实际执行是交给TaskExecutor的。
在需要异步执行的类上标注@Async,比如,我们现在有一个需要监听的事件
public class HelloEven extends ApplicationEvent {
private String name;
public HelloEven(Object source,String name) {
super(source);
this.name = name;
}
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
}
异步监听器实现
@Component
public class HelloListen {
@EventListener
// 定义的线程池名称
@Async("taskExecutor")
public void run(HelloEven even) {
System.out.println("==== " + Thread.currentThread().getName() + " ====" + even.getName());
}
}
// 输出结果
// ==== Async-Service-1 ====hello,baby
定义线程池
/** * 默认情况下,在创建了线程池后,线程池中的线程数为0,当有任务来之后,就会创建一个线程去执行任务, * 当线程池中的线程数目达到corePoolSize后,就会把到达的任务放到缓存队列当中; * 当队列满了,就继续创建线程,当线程数量大于等于maxPoolSize后,开始使用拒绝策略拒绝 */
@Configuration
@EnableAsync
public class ThreadPoolTaskConfig {
/** * 核心线程数(默认线程数) */
private static final int corePoolSize = 20;
/** * 最大线程数 */
private static final int maxPoolSize = 100;
/** * 允许线程空闲时间(单位:默认为秒) */
private static final int keepAliveTime = 10;
/** * 缓冲队列大小 */
private static final int queueCapacity = 200;
/** * 线程池名前缀 */
private static final String threadNamePrefix = "Async-Service-";
@Bean("taskExecutor") // bean的名称,默认为首字母小写的方法名
public ThreadPoolTaskExecutor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setKeepAliveSeconds(keepAliveTime);
executor.setThreadNamePrefix(threadNamePrefix);
// 线程池对拒绝任务的处理策略
// CallerRunsPolicy:由调用线程(提交任务的线程)处理该任务
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
// 初始化
executor.initialize();
return executor;
}
}
如下方式会使@Async失效
- 异步方法使用static修饰
- 异步类没有使用@Component注解(或其他注解)导致spring无法扫描到异步类
- 异步方法不能与被调用的异步方法在同一个类中
- 类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象
- 如果使用SpringBoot框架必须在启动类中增加@EnableAsync注解
边栏推荐
猜你喜欢

亿流量大考(3):不加机器,如何抗住每天百亿级高并发流量?

I was rejected by the leader for a salary increase, and my anger rose by 9.5K after switching jobs. This is my mental journey

直播带货为农产品开拓销售渠道

社区分享|腾讯海外游戏基于JumpServer构建游戏安全运营能力

【游戏建模模型制作全流程】ZBrush蜥蜴模型雕刻教程

web3.js

【游戏建模模型制作全流程】使用ZBrush制作骷髅王

SSM整合完整流程讲解

【字符串函数内功修炼】strcpy + strcat + strcmp(一)

被领导拒绝涨薪申请,跳槽后怒涨9.5K,这是我的心路历程
随机推荐
自从新来了个字节20K出来的,就见识到了什么是天花板
特征工程资料汇总
容联云发送短信验证码
从“草原牛”到“数字牛”:蒙牛的数字化转型之道
吐槽 | 参加IT培训的正确姿势
[Cultivation of internal skills of string functions] strlen + strstr + strtok + strerror (3)
Service Mesh landing path
ffplay视频播放原理分析
七牛云图片上传
go语言的日志实现(打印日志、日志写入文件、日志切割)
一点点读懂cpufreq(一)
One trick to cure pycharm DEBUG error UnicodeDecodeError: 'utf-8' codec can't decode
一点点读懂regulator(三)
Service Mesh落地路径
【3D建模制作技巧分享】ZBrush模型如何添加不同材质
App测试和Web测试的区别
If you can't get your heart, use "distributed lock" to lock your people
学生管理系统架构设计
Controller层代码这么写,简洁又优雅!
一点点读懂regulator(四)