关于SpringBoot使用@Async的总结
SpringBoot使用@Async总结
注意事项:
如下方式会使@Async失效
1. 异步方法使用static修饰
2. 异步类没有使用@Component注解(或其他注解)导致spring无法扫描到异步类
3. 异步方法不能与异步方法在同一个类中
4. 类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象
5. 如果使用SpringBoot框架必须在启动类中增加@EnableAsync注解
6. 在Async 方法上标注@Transactional是没用的。 在Async 方法调用的方法上标注@Transactional 有效。
SpringBoot实现异步(Async)接口
1. 启动类引入@EnableAsync注解
@SpringBootApplication
@EnableAsync
public class Application{
public static void main(String[] args) {
SpringApplication.run(Application.class, args);
}
}
2. 建立异步任务类
我们建了3个异步任务,分别延迟1s,2s,3s
@Component
public class AsyncTask {
@Async
public void task1() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(1000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task1任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
@Async
public void task2() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(2000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task2任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
@Async
public void task3() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
Thread.sleep(3000);
long currentTimeMillis1 = System.currentTimeMillis();
System.out.println("task3任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
}
}
3. 建立测试接口
@RestController
@RequestMapping("/test")
public class TestController {
@Autowired
private AsyncTask asyncTask;
@RequestMapping("/async")
public String doTask() throws InterruptedException{
long currentTimeMillis = System.currentTimeMillis();
asyncTask.task1();
asyncTask.task2();
asyncTask.task3();
long currentTimeMillis1 = System.currentTimeMillis();
return "task任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
}
}
启动SpringBoot服务,访问/test/async接口,能看到任务耗时只有1s

查看控制台,发现异步task也成功执行了!

以上为个人经验,希望能给大家一个参考,也希望大家多多支持脚本之家。
相关文章
Spring init-method与destroy-method属性的用法解析
这篇文章主要介绍了Spring init-method与destroy-method属性的用法,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教2021-08-08
SpringBoot实现对超大文件进行异步压缩下载的使用示例
在Web应用中,文件下载功能是一个常见的需求,本文介绍了SpringBoot实现对超大文件进行异步压缩下载的使用示例,具有一定的参考价值,感兴趣的可以了解一下,2023-09-09
Java BasePooledObjectFactory 对象池化技术的使用
这篇文章主要介绍了Java BasePooledObjectFactory 对象池化技术,本文给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下2023-04-04


最新评论