springboot中@EnableAsync与@Async基本使用

背景

开发时发现,同一个接口方法对获取的数据需要入库,之后再返回,结构复杂的话,解析入库的过程非常耗时间,所以开启一个异步线程去执行入库任务。

关键注解

@EnableAsync:启用 Spring 异步方法执行功能
@Async:异步方法

启动类需添加@EnableAsync开启对异步的支持

public static int[] num = null;
	//模拟耗时
	@Async
    public void startThread(){
        try{
            synchronized (num){
                for (int a:num) {
                    Thread.sleep(1000);
                    System.err.println(a);
                }
            }
        }catch (Exception e){}
    }
    public void test(){
        System.err.println(Thread.currentThread().getName());
        ThreadStart.num = new int[]{0,1,2};
        start.startThread();
        System.err.println("执行完成,客户端返回结果");
    }

实现

正常同步执行顺序
在这里插入图片描述
添加@Async之后执行(发现执行顺序已经发生变化)
在这里插入图片描述
@Async失效的场景

  1. 异步方法使用static修饰
  2. 异步类没有使用@Component注解(或其他注解)导致spring无法扫描到异步类
  3. 异步方法不能与异步方法在同一个类中
  4. 类中需要使用@Autowired或@Resource等注解自动注入,不能自己手动new对象
  5. 使用@Async时不能有返回值
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值