当前位置:   article > 正文

SpringBoot2.0之异步任务(async)和 java8 CompletableFuture的调用_springboot completablefuture.supplyasync

springboot completablefuture.supplyasync

1.我们先介绍java8 的异步调用:CompletableFuture

用CompletableFuture.supplyAsync()定义要执行的异步任务

  1. public class java8Async {
  2. public static void main(String[] args) {
  3. ExecutorService executor = Executors.newFixedThreadPool(10);
  4. // CompletableFuture.supplyAsync(),定义要执行的异步任务
  5. CompletableFuture.supplyAsync(new Supplier<String>() {
  6. @Override
  7. public String get() {
  8. // TODO Auto-generated method stub
  9. try {
  10. System.out.println("任务1");
  11. // 睡眠1s
  12. TimeUnit.SECONDS.sleep(1);
  13. System.out.println("任务2");
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. return "返回数据async";
  18. }
  19. }, executor);
  20. // return
  21. System.out.println("任务执行完成");
  22. }
  23. }

执行结果:

 

当异步任务需要返回数据那怎么办呢?

用cupdResult.thenAccept(new Consumer<String>() , 重写accept()方法去定义回调函数

  1. public class java8Async {
  2. public static void main(String[] args) {
  3. ExecutorService executor = Executors.newFixedThreadPool(10);
  4. // CompletableFuture.supplyAsync(),定义要执行的异步任务
  5. CompletableFuture<String> asyncResult = CompletableFuture.supplyAsync(new Supplier<String>() {
  6. @Override
  7. public String get() {
  8. // TODO Auto-generated method stub
  9. try {
  10. System.out.println("任务1");
  11. // 睡眠1s
  12. TimeUnit.SECONDS.sleep(1);
  13. System.out.println("任务2");
  14. } catch (Exception e) {
  15. e.printStackTrace();
  16. }
  17. return "返回数据async";
  18. }
  19. }, executor);
  20. // asyncResult.thenAccept(new Consumer<String>() , 重写accept()方法去定义回调函数
  21. asyncResult.thenAccept(new Consumer<String>() {
  22. public void accept(String arg0) {
  23. System.out.println("return =" + arg0);
  24. }
  25. });
  26. // return
  27. System.out.println("任务执行完成");
  28. }
  29. }

执行结果:

2.我们介绍springboot的异步任务:springboot给我们提供了注解方法,在启动类上添加@EnableAsync注解,在需要用到异步任务的实现方法上添加@Async注解,然后就可以用了,详情如下:

启动类:添加@EnableAsync注解

  1. package com.async;
  2. import org.springframework.boot.SpringApplication;
  3. import org.springframework.boot.autoconfigure.SpringBootApplication;
  4. import org.springframework.scheduling.annotation.EnableAsync;
  5. import org.springframework.transaction.annotation.EnableTransactionManagement;
  6. /**
  7. * @ClassName: OtherApplication
  8. * @Description: TODO()
  9. * @author lixin(1309244704@qq.com)
  10. * @date 2018年10月13日 下午4:43:35
  11. * @version V1.0
  12. */
  13. @SpringBootApplication
  14. @EnableTransactionManagement
  15. @EnableAsync
  16. public class OtherApplication {
  17. public static void main(String[] args) {
  18. SpringApplication.run(OtherApplication.class, args);
  19. }
  20. }

然后在你需要异步调用的方法上添加注解

  1. package com.async.boot;
  2. import java.util.concurrent.Future;
  3. import org.springframework.scheduling.annotation.Async;
  4. import org.springframework.scheduling.annotation.AsyncResult;
  5. import org.springframework.stereotype.Service;
  6. import org.springframework.transaction.annotation.Transactional;
  7. /**
  8. * @ClassName: AsyncAfterServiceImpl
  9. * @Description: TODO()
  10. * @author lixin(1309244704@qq.com)
  11. * @date 2018年10月13日 下午4:50:38
  12. * @version V1.0
  13. */
  14. @Service
  15. public class AsyncAfterServiceImpl implements AsyncAfterService{
  16. @Transactional
  17. @Override
  18. @Async
  19. public Future<String> asyncAfterOne() throws InterruptedException {
  20. System.err.println("asyncAfterOne任务以执行");
  21. return new AsyncResult<String>("asyncAfterOne执行完毕");
  22. }
  23. @Transactional
  24. @Override
  25. @Async
  26. public Future<String> asyncAfterTwo() throws InterruptedException {
  27. long currentTimeMillis = System.currentTimeMillis();
  28. Thread.sleep(3000);
  29. long currentTimeMillis1 = System.currentTimeMillis();
  30. System.err.println("asyncAfterTwo任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
  31. return new AsyncResult<String>("asyncAfterTwo执行完毕");
  32. }
  33. @Transactional
  34. @Override
  35. @Async
  36. public Future<String> asyncAfterThree() throws InterruptedException {
  37. long currentTimeMillis = System.currentTimeMillis();
  38. Thread.sleep(6000);
  39. long currentTimeMillis1 = System.currentTimeMillis();
  40. System.err.println("asyncAfterThree任务耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms");
  41. return new AsyncResult<String>("asyncAfterThree执行完毕");
  42. }
  43. }

然后是调用类:

  1. package com.async.boot;
  2. import java.util.concurrent.ExecutionException;
  3. import java.util.concurrent.Future;
  4. import org.springframework.beans.factory.annotation.Autowired;
  5. import org.springframework.stereotype.Service;
  6. import org.springframework.transaction.annotation.Transactional;
  7. /**
  8. * @ClassName: AsyncServiceImpl
  9. * @Description: TODO()
  10. * @author lixin(1309244704@qq.com)
  11. * @date 2018年10月13日 下午4:54:15
  12. * @version V1.0
  13. */
  14. @Service
  15. public class AsyncServiceImpl implements AsyncService{
  16. @Autowired
  17. private AsyncAfterService asyncAfterService;
  18. @Transactional
  19. @Override
  20. public String asyncOne() throws InterruptedException {
  21. long currentTimeMillis = System.currentTimeMillis();
  22. asyncAfterService.asyncAfterOne();
  23. asyncAfterService.asyncAfterTwo();
  24. asyncAfterService.asyncAfterThree();
  25. long currentTimeMillis1 = System.currentTimeMillis();
  26. return "asyncAfter任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
  27. }
  28. @Transactional
  29. @Override
  30. public String asyncTwo() throws InterruptedException, ExecutionException {
  31. long currentTimeMillis = System.currentTimeMillis();
  32. Future<String> two = asyncAfterService.asyncAfterTwo();
  33. Future<String> three = asyncAfterService.asyncAfterThree();
  34. String result = null;
  35. while (true) {
  36. if(two.isDone() && three.isDone()) {
  37. System.err.println(two.get());
  38. System.err.println(three.get());
  39. // 两个任务都调用完成,跳出循环
  40. break;
  41. }
  42. Thread.sleep(1000);
  43. }
  44. long currentTimeMillis1 = System.currentTimeMillis();
  45. result = "asyncAfter任务总耗时:"+(currentTimeMillis1-currentTimeMillis)+"ms";
  46. return result;
  47. }
  48. }

然后是测试类:

  1. package com.async;
  2. import java.util.concurrent.ExecutionException;
  3. import org.junit.Test;
  4. import org.junit.runner.RunWith;
  5. import org.springframework.beans.factory.annotation.Autowired;
  6. import org.springframework.boot.autoconfigure.EnableAutoConfiguration;
  7. import org.springframework.boot.test.context.SpringBootTest;
  8. import org.springframework.test.context.junit4.SpringRunner;
  9. import com.async.boot.AsyncService;
  10. @RunWith(SpringRunner.class)
  11. @SpringBootTest(classes = OtherApplication.class, webEnvironment = SpringBootTest.WebEnvironment.RANDOM_PORT)
  12. @EnableAutoConfiguration
  13. public class AsyncTest {
  14. @Autowired
  15. private AsyncService asyncService;
  16. @Test
  17. public void asyncOne() throws InterruptedException {
  18. System.err.println(asyncService.asyncOne());
  19. Thread.sleep(8000);
  20. }
  21. @Test
  22. public void asyncTwo() throws InterruptedException, ExecutionException {
  23. System.err.println(asyncService.asyncTwo());
  24. }
  25. }

方法执行结果分别如下:

 

 github项目demo地址:https://github.com/LX1309244704/SpringBoot-master/tree/master/springboot-async

 

声明:本文内容由网友自发贡献,转载请注明出处:【wpsshop】
推荐阅读
相关标签
  

闽ICP备14008679号