400 028 6601

建站动态

根据您的个性需求进行定制 先人一步 抢占小程序红利时代

怎么在SpringBoot中实现异步调用@Async

这期内容当中小编将会给大家带来有关怎么在SpringBoot中实现异步调用@Async,文章内容丰富且以专业的角度为大家分析和叙述,阅读完这篇文章希望大家可以有所收获。

成都创新互联公司专注为客户提供全方位的互联网综合服务,包含不限于网站制作、成都网站建设、河东网络推广、微信小程序、河东网络营销、河东企业策划、河东品牌公关、搜索引擎seo、人物专访、企业宣传片、企业代运营等,从售前售中售后,我们都将竭诚为您服务,您的肯定,是我们最大的嘉奖;成都创新互联公司为所有大学生创业者提供河东建站搭建服务,24小时服务热线:18982081108,官方网址:www.cdcxhl.com

一、@Async使用演示

@Async是Spring内置注解,用来处理异步任务,在SpringBoot中同样适用,且在SpringBoot项目中,除了boot本身的starter外,不需要额外引入依赖。

而要使用@Async,需要在启动类上加上@EnableAsync主动声明来开启异步方法。

@EnableAsync
@SpringBootApplication
public class SpringbootApplication {

  public static void main(String[] args) {
    SpringApplication.run(SpringbootApplication.class, args);
  }
}

现假设有3个任务需要去处理,分别对应AsyncTask类的taskOne、taskTwo、taskThree方法,这里做了线程的sleep来模拟实际运行。

@Slf4j
@Component
public class AsyncTask {

  private Random random = new Random();
  
  public void taskOne() throws InterruptedException {
    long start = System.currentTimeMillis();
    Thread.sleep(random.nextInt(10000));
    long end = System.currentTimeMillis();
    log.info("任务一执行完成耗时{}秒", (end - start)/1000f);
  }
  
  public void taskTwo() throws InterruptedException {
    long start = System.currentTimeMillis();
    Thread.sleep(random.nextInt(10000));
    long end = System.currentTimeMillis();
    log.info("任务二执行完成耗时{}秒", (end - start)/1000f);
  }
  
  public void taskThree() throws InterruptedException {
    long start = System.currentTimeMillis();
    Thread.sleep(random.nextInt(10000));
    long end = System.currentTimeMillis();
    log.info("任务三执行完成耗时{}秒", (end - start)/1000f);
  }
}

然后编写测试类,由于@Async注解需要再Spring容器启动后才能生效,所以这里讲测试类放到了SpringBoot的test包下,使用了SpringBootTest。

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootApplication.class)
public class AsyncTaskTest {

  @Autowired
  private AsyncTask asyncTask;

  @Test
  public void doAsyncTasks(){
    try {
      long start = System.currentTimeMillis();
      asyncTask.taskOne();
      asyncTask.taskTwo();
      asyncTask.taskThree();
      Thread.sleep(5000);
      long end = System.currentTimeMillis();
      log.info("主程序执行完成耗时{}秒", (end - start)/1000f);
    } catch (InterruptedException e) {
      e.printStackTrace();
    }
  }

}

运行测试方法,可以在控制台看到任务一二三按顺序执行,最后主程序完成,这和我们的预期一样,因为我们没有任何额外的处理,他们就是普通的方法,按编码顺序依次执行。

怎么在SpringBoot中实现异步调用@Async

而如果要使任务并发执行,我们只需要在任务方法上使用@Async注解即可,需要注意的是@Async所修饰的方法不要定义为static类型,这样异步调用不会生效。

@Slf4j
@Component
public class AsyncTask {

  private Random random = new Random();

  //@Async所修饰的函数不要定义为static类型,这样异步调用不会生效
  @Async
  public void taskOne() throws InterruptedException {
    long start = System.currentTimeMillis();
    Thread.sleep(random.nextInt(10000));
    long end = System.currentTimeMillis();
    log.info("任务一执行完成耗时{}秒", (end - start)/1000f);
  }

  @Async
  public void taskTwo() throws InterruptedException {
    long start = System.currentTimeMillis();
    Thread.sleep(random.nextInt(10000));
    long end = System.currentTimeMillis();
    log.info("任务二执行完成耗时{}秒", (end - start)/1000f);
  }

  @Async
  public void taskThree() throws InterruptedException {
    long start = System.currentTimeMillis();
    Thread.sleep(random.nextInt(10000));
    long end = System.currentTimeMillis();
    log.info("任务三执行完成耗时{}秒", (end - start)/1000f);
  }

}

然后我们在运行测试类,这个时候输出可能就五花八门了,任意任务都可能先执行完成,也有可能有的方法因为主程序关闭而没有输出。

怎么在SpringBoot中实现异步调用@Async

二、Future获取异步执行结果

上面演示了@Async,但是有时候除了需要任务并发调度外,我们还需要获取任务的返回值,且在多任务都执行完成后再结束主任务,这个时候又该怎么处理呢?

在多线程里通过Callable和Future可以获取返回值,这里也是类似的,我们使用Future返回方法的执行结果,AsyncResult是Future的一个实现类。

@Slf4j
@Component
public class FutureTask {

  private Random random = new Random();

  //@Async所修饰的函数不要定义为static类型,这样异步调用不会生效
  @Async
  public Future taskOne() throws InterruptedException {
    long start = System.currentTimeMillis();
    Thread.sleep(random.nextInt(10000));
    long end = System.currentTimeMillis();
    log.info("任务一执行完成耗时{}秒", (end - start)/1000f);
    return new AsyncResult <>("任务一Ok");
  }

  @Async
  public Future taskTwo() throws InterruptedException {
    long start = System.currentTimeMillis();
    Thread.sleep(random.nextInt(10000));
    long end = System.currentTimeMillis();
    log.info("任务二执行完成耗时{}秒", (end - start)/1000f);
    return new AsyncResult <>("任务二OK");
  }

  @Async
  public Future taskThree() throws InterruptedException {
    long start = System.currentTimeMillis();
    Thread.sleep(random.nextInt(10000));
    long end = System.currentTimeMillis();
    log.info("任务三执行完成耗时{}秒", (end - start)/1000f);
    return new AsyncResult <>("任务三Ok");
  }
}

在AsyncResult中:

@Slf4j
@RunWith(SpringRunner.class)
@SpringBootTest(classes = SpringbootApplication.class)
public class AsyncTaskTest {

  @Autowired
  private FutureTask futureTask;

  @Test
  public void doFutureTasks(){
    try {
      long start = System.currentTimeMillis();
      Future  future1 = futureTask.taskOne();
      Future  future2 = futureTask.taskTwo();
      Future  future3 = futureTask.taskThree();
      //3个任务执行完成之后再执行主程序
      do {
        Thread.sleep(100);
      } while (future1.isDone() && future2.isDone() && future3.isDone());
      log.info("获取异步方法的返回值:{}", future1.get());
      Thread.sleep(5000);
      long end = System.currentTimeMillis();
      log.info("主程序执行完成耗时{}秒", (end - start)/1000f);
    } catch (InterruptedException e) {
      e.printStackTrace();
    } catch (ExecutionException e) {
      e.printStackTrace();
    }
  }
}

运行测试类,我们可以看到任务一二三异步执行了,主任务最后执行完成,而且可以获取到任务的返回信息。

怎么在SpringBoot中实现异步调用@Async

上述就是小编为大家分享的怎么在SpringBoot中实现异步调用@Async了,如果刚好有类似的疑惑,不妨参照上述分析进行理解。如果想知道更多相关知识,欢迎关注创新互联行业资讯频道。


文章标题:怎么在SpringBoot中实现异步调用@Async
文章位置:http://mzwzsj.com/article/igcopd.html

其他资讯

让你的专属顾问为你服务