@Async 没有异步执行

709 阅读2分钟

Spring 异步执行Async简介

Spring中用@Async注解标记的方法,称为异步方法,其实就相当于我们自己在当前方法里面:new Thread(()-> System.out.println("hello world !"))。

按@Async注解使用的基本方法:

在方法上添加@Async注解;

所使用的@Async注解方法的类对象应该是Spring容器管理的bean对象;

调用异步方法类上需要配置上注解@EnableAsync

失效原因

  1. @SpringBootApplication启动类当中没有添加@EnableAsync注解。
  2. 异步方法使用注解@Async的返回值只能为void或者Future。
  3. 没有走Spring的代理类。因为@Transactional和@Async注解的实现都是基于Spring的AOP,而AOP的实现是基于动态代理模式实现的。那么注解失效的原因就很明显了,有可能因为调用方法的是对象本身而不是代理对象,因为没有经过Spring容器管理。

问题代码:

一个类中调用了本类的方法,没有走代理对象。

    @PostConstruct
    public void test(){
        Long a = System.currentTimeMillis();
        try {
            test1();
            test2();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        System.out.println(">>>>>>>"+(System.currentTimeMillis()-a));
    }

    @Async("")
    public  void test1() throws InterruptedException {
        System.out.println(1);
        Thread.sleep(10000);
        System.out.println(2);
    }
    @Async("")
    public  void test2() throws InterruptedException {
        System.out.println(3);
        Thread.sleep(10000);
        System.out.println(4);
    }

执行结果就是

1->2->3->4

解决:

增加接口类和实现类

public interface DataService {


    public  void test1();


    public  void test2();
}

实现类:

@Service
public class DataServiceImpl implements DataService {

    @Override
    @Async("asyncServiceExecutor")
    public void test1() {
        System.out.println(1);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(2);
    }

    @Override
    @Async("asyncServiceExecutor")
    public void test2() {
        System.out.println(3);
        try {
            Thread.sleep(10000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println(4);
    }
}

调用:

    @Autowired
    private DataService dataService;
    @PostConstruct
    public void test(){
        Long a = System.currentTimeMillis();
        dataService.test1();
        dataService.test2();

        System.out.println(">>>>>>>"+(System.currentTimeMillis()-a));
    }

执行结果就是

1->3->2->4 或者1->3->4->2

总结一下

在Spring中,@Async这个注解用于标记的异步的方法。方法上一旦标记了这个方法,当其它线程调用这个方法时,就会开启一个新的线程去异步处理业务逻辑。

简单的把@Async注解放到Bean的方法上就会使用不同的线程运行,也就是说,调用者执行此方法不用一直等待整个方法执行完毕。

在Spring中比较有趣的一点就是事件机制也支持异步处理,如果你想这样使用的话。

让我们开始使用JAVA的注解配置开启异步处理机制,只需要简单的加上@EnableAsync注解到配置类上即可