SpringBoot中使用异步方法优化Service逻辑,提高接口响应速度

程序员的成长之路

共 6097字,需浏览 13分钟

 ·

2021-11-04 19:24

程序员的成长之路
互联网/程序员/技术/资料共享 
关注


阅读本文大概需要 5 分钟。

来自:blog.csdn.net/weixin_43441509/article/details/119855613

1. 为什么需要异步方法?

先说结论: 合理使用异步方法可以让业务接口快到飞起!
异步方法适用于逻辑与逻辑之间可以相互分割互不影响的业务中, 如生成验证码和发送验证码组成的业务, 其实无需等到真正发送成功验证码才对客户端进行响应, 可以让短信发送这一耗时操作转为异步执行, 解耦耗时操作和核心业务;
同理还有文章阅读的业务逻辑 = 查询文章详情 + 更新文章阅读量后再响应客户端, 其实也无需等到阅读量更新后才响应文章详情给客户端, 用户查看文章是主要逻辑, 而文章阅读量更新是次要逻辑, 况且阅读量就算更新失败一点数据偏差也不会影响用户阅读因此这两个数据库操作之间的一致性是较弱的, 这类都能用异步事件去优化.
所以说: 恰当的在我们的Service中加入异步方法能大大提高接口的响应速度, 提升用户体验!
同步执行(同在一个线程中):
异步执行(开启额外线程来执行):

2. SpringBoot中的异步方法支持

其实, 在SpringBoot中并不需要我们自己去创建维护线程或者线程池来异步的执行方法, SpringBoot已经提供了异步方法支持注解.
  1. @EnableAsync // 使用异步方法时需要提前开启(在启动类上或配置类上)

  2. @Async // 被async注解修饰的方法由SpringBoot默认线程池(SimpleAsyncTaskExecutor)执行

比如使用Spring的异步支持实现文章查询并增加阅读量
Service层:
  1. @Service

  2. public class ArticleServiceImpl {

  3.     // 查询文章

  4.     public String selectArticle() {

  5.         // TODO 模拟文章查询操作

  6.         System.out.println("查询任务线程"+Thread.currentThread().getName());

  7.         return "文章详情";

  8.     }

  9.     // 文章阅读量+1

  10.     @Async

  11.     public void updateReadCount() {

  12.         // TODO 模拟耗时操作

  13.         try {

  14.             Thread.sleep(3000);

  15.         } catch (InterruptedException e) {

  16.             e.printStackTrace();

  17.         }

  18.         System.out.println("更新任务线程"+Thread.currentThread().getName());

  19.     }

  20. }

Controller层:
  1. @RestController

  2. public class AsyncTestController {

  3.     @Autowired

  4.     private ArticleServiceImpl articleService;

  5.     /**

  6.      * 模拟获取文章后阅读量+1

  7.      */

  8.     @PostMapping("/article")

  9.     public String getArticle() {

  10.         // 查询文章

  11.         String article = articleService.selectArticle();

  12.         // 阅读量+1

  13.         articleService.updateReadCount();

  14.         System.out.println("文章阅读业务执行完毕");

  15.         return article;

  16.     }

  17. }

测试结果: 我们可以感受到接口响应速度大大提升, 而且从日志中key看到两个执行任务是在不同的线程中执行的

3. 自定义线程池执行异步方法

SpringBoot为我们默认提供了线程池(SimpleAsyncTaskExecutor)来执行我们的异步方法, 我们也可以自定义自己的线程池.
第一步配置自定义线程池
  1. @EnableAsync // 开启多线程, 项目启动时自动创建

  2. @Configuration

  3. public class AsyncConfig {

  4.     @Bean("customExecutor")

  5.     public ThreadPoolTaskExecutor asyncOperationExecutor() {

  6.         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

  7.         // 设置核心线程数

  8.         executor.setCorePoolSize(8);

  9.         // 设置最大线程数

  10.         executor.setMaxPoolSize(20);

  11.         // 设置队列大小

  12.         executor.setQueueCapacity(Integer.MAX_VALUE);

  13.         // 设置线程活跃时间(秒)

  14.         executor.setKeepAliveSeconds(60);

  15.         // 设置线程名前缀+分组名称

  16.         executor.setThreadNamePrefix("AsyncOperationThread-");

  17.         executor.setThreadGroupName("AsyncOperationGroup");

  18.         // 所有任务结束后关闭线程池

  19.         executor.setWaitForTasksToCompleteOnShutdown(true);

  20.         // 初始化

  21.         executor.initialize();

  22.         return executor;

  23.     }

  24. }

第二步, 在@Async注解上指定执行的线程池即可
  1. // 文章阅读量+1

  2. @Async("customExecutor")

  3. public void updateReadCount() {

  4.     // TODO 模拟耗时操作

  5.     try {

  6.         Thread.sleep(3000);

  7.     } catch (InterruptedException e) {

  8.         e.printStackTrace();

  9.     }

  10.     System.out.println("更新文章阅读量线程"+Thread.currentThread().getName());

  11. }

5. 如何捕获(无返回值的)异步方法中的异常

以实现AsyncConfigurer接口的getAsyncExecutor方法和getAsyncUncaughtExceptionHandler方法改造配置类
自定义异常处理类CustomAsyncExceptionHandler
  1. @EnableAsync // 开启多线程, 项目启动时自动创建

  2. @Configuration

  3. public class AsyncConfig implements AsyncConfigurer {

  4.     @Override

  5.     public Executor getAsyncExecutor() {

  6.         ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();

  7.         // 设置核心线程数

  8.         executor.setCorePoolSize(8);

  9.         // 设置最大线程数

  10.         executor.setMaxPoolSize(20);

  11.         // 设置队列大小

  12.         executor.setQueueCapacity(Integer.MAX_VALUE);

  13.         // 设置线程活跃时间(秒)

  14.         executor.setKeepAliveSeconds(60);

  15.         // 设置线程名前缀+分组名称

  16.         executor.setThreadNamePrefix("AsyncOperationThread-");

  17.         executor.setThreadGroupName("AsyncOperationGroup");

  18.         // 所有任务结束后关闭线程池

  19.         executor.setWaitForTasksToCompleteOnShutdown(true);

  20.         // 初始化

  21.         executor.initialize();

  22.         return executor;

  23.     }

  24.     @Override

  25.     public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {

  26.         return new CustomAsyncExceptionHandler();

  27.     }

  28. }

  1. public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {

  2.  

  3.     @Override

  4.     public void handleUncaughtException(Throwable throwable, Method method, Object... obj) {

  5.         System.out.println("异常捕获---------------------------------");

  6.         System.out.println("Exception message - " + throwable.getMessage());

  7.         System.out.println("Method name - " + method.getName());

  8.         for (Object param : obj) {

  9.             System.out.println("Parameter value - " + param);

  10.         }

  11.         System.out.println("异常捕获---------------------------------");

  12.     }

  13.      

  14. }

5. 如何获取(有返回值)异步方法的返回值

使用Future类及其子类来接收异步方法返回值
注意:
  • 无返回值的异步方法抛出异常不会影响Controller的主要业务逻辑

  • 有返回值的异步方法抛出异常会影响Controller的主要业务逻辑

  1. // 异步方法---------------------------------------------------------------------

  2. @Async

  3.     public CompletableFuture updateReadCountHasResult() {

  4.         // TODO 模拟耗时操作

  5.         try {

  6.             Thread.sleep(3000);

  7.         } catch (InterruptedException e) {

  8.             e.printStackTrace();

  9.         }

  10.         System.out.println("更新文章阅读量线程"+Thread.currentThread().getName());

  11.         return CompletableFuture.completedFuture(100 + 1);

  12.     }

  13. // Controller调用---------------------------------------------------------------------

  14. @GetMapping("/article")

  15. public String getArticle() throws ExecutionException, InterruptedException {

  16.     // 查询文章

  17.     String article = articleService.selectArticle();

  18.     // 阅读量+1

  19.     CompletableFuture future = articleService.updateReadCountHasResult();

  20.     int count = 0;

  21.     // 循环等待异步请求结果

  22.     while (true) {

  23.         if(future.isCancelled()) {

  24.             System.out.println("异步任务取消");

  25.             break;

  26.         }

  27.         if (future.isDone()) {

  28.             count = future.get();

  29.             System.out.println(count);

  30.             break;

  31.         }

  32.     }

  33.     System.out.println("文章阅读业务执行完毕");

  34.     return article + count;

  35. }

6. 异步方法带来的问题/拓展

  • 异步方法只能声明在Service方法中在Controller直接调用才会生效, 异步方法被同级Service方法调用不会生效, 很奇怪?

  • 异步方法 + 事务能顺利执行吗? 或许事务操作应该和异步操作分离开, 被Controller层调用时事务操作在前, 异步操作在后

  • 异步方法执行失败后对Controller前半部分的非异步操作无影响, 因此说异步方法在整个业务逻辑中不是100%可靠的, 对于强一致性的业务来说不适用

  • 还是消息中间件更为强大, RabbitMQ, Kafka…

推荐阅读:

火遍全国的网络热梗“yyds”,创造者被判刑3年

Hbase与MySQL对比,区别是什么?

朕已阅 

浏览 32
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报
评论
图片
表情
推荐
点赞
评论
收藏
分享

手机扫一扫分享

分享
举报