背景

需要把一些调用其它服务器的执行时间比较长的方法异步化,这样就不要等待这些方法执行完后才执行其它的方法的。可以转换为异步方法的条件是

1. 它没有返回值,或者有返回值但是返回值和接下来要执行的代码没有关系。

2. 它的错误和调用它的方法没有关系,或者说它的错误它自己可以处理。

1. Maven 中依赖

     <parent><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-parent</artifactId><version>2.6.2</version><relativePath/></parent><dependencies><dependency><groupId>org.springframework.boot</groupId><artifactId>spring-boot-starter-web</artifactId></dependency></dependencies>

1. 开启异步线程

在SpringBoot的启动类上面加上@EnableAsync

@SpringBootApplication
@Import(value = SpringAsyncConfig.class)
public class SpringBootClient {public static void main(String[] args) {SpringApplication.run( SpringBootClient.class, args );}
}

2.  实例化自己的线程池

虽然SpringBoot已经帮我们做了默认配置,但是为了要掌握具体的内容还是可以自定义配置

@Configuration
@EnableAsync
public class SpringAsyncConfig implements AsyncConfigurer  {@Bean(name = "threadPoolTaskExecutor")public Executor threadPoolTaskExecutor() {return new ThreadPoolTaskExecutor();}public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {return new CustomAsyncExceptionHandler();}
}

3. 还有自定义错误处理类

public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {@Overridepublic void handleUncaughtException(Throwable throwable, Method method, Object... obj) {System.out.println("Exception message - " + throwable.getMessage());System.out.println("Method name - " + method.getName());for (Object param : obj) {System.out.println("Parameter value - " + param);}}}

4. 异步方法的使用

asyncMethodWithVoidReturnType方法:不返回值

asyncMethodWithReturnType方法:有返回值

@Component
public class AsyncAnnotationExample {@Asyncpublic void asyncMethodWithVoidReturnType() {System.out.println("Execute method asynchronously. " + Thread.currentThread().getName());System.out.println(1/0);}@Asyncpublic Future<String> asyncMethodWithReturnType() {System.out.println("Execute method asynchronously - " + Thread.currentThread().getName());try {Thread.sleep(5000);return new AsyncResult<String>("hello world !!!!");} catch (InterruptedException e) {//}return null;}}

5. 写个Controller类做测试

test1接口测试有返回的异步方法

test2接口测试无返回的异步方法。

@RestController
public class AsyncController {@Autowiredprivate AsyncAnnotationExample asyncAnnotationExample;@RequestMapping("/test1")public String test1() {try {System.out.println("Invoking an asynchronous method. " + Thread.currentThread().getName());Future<String> future = asyncAnnotationExample.asyncMethodWithReturnType();while (true) {if (future.isDone()) {System.out.println("Result from asynchronous process - " + future.get());break;}System.out.println("Continue doing something else. ");Thread.sleep(1000);}}catch(Exception e) {e.printStackTrace();}return "test1";}@RequestMapping("/test2")public String test2() {System.out.println("Invoking an asynchronous method. " + Thread.currentThread().getName());asyncAnnotationExample.asyncMethodWithVoidReturnType();return "test2";}}

Spring Boot @Async 简单实践相关推荐

  1. Spring Boot 2.0:Docker Compose + Spring Boot + Nginx + Mysql 实践

    Spring Boot 2.0:Docker Compose + Spring Boot + Nginx + Mysql 实践 Spring Boot + Nginx + Mysql 是实际工作中最常 ...

  2. springboot导入项目依赖报错_使用Spring Boot很简单,go!!!

    Spring Boot依赖 使用Spring Boot很简单,先添加基础依赖包,有以下两种方式 1. 继承spring-boot-starter-parent项目    org.springframe ...

  3. Spring Boot统一异常处理实践

    Spring Boot统一异常处理实践 参考文章: (1)Spring Boot统一异常处理实践 (2)https://www.cnblogs.com/fundebug/p/springboot-ex ...

  4. Spring Boot Mybatis简单使用

    Spring Boot Mybatis简单使用 步骤说明 build.gradle:依赖添加 application.properties:配置添加 代码编写 测试 build.gradle:依赖添加 ...

  5. Spring Boot 缓存应用实践

    点击上方蓝色"程序猿DD",选择"设为星标" 回复"资源"获取独家整理的学习资料! 来源:cnblogs.com/jeffwongishan ...

  6. Spring Boot学习笔记-实践建言

    2019独角兽企业重金招聘Python工程师标准>>> 本文延续<Spring Boot学习笔记-快速示例>,从开发指南中摘出一些实践经验可供参考.这也是笔者看到的眼前一 ...

  7. 【站在微笑的肩上】Spring Boot 2 (五):Docker Compose + Spring Boot + Nginx + Mysql 实践

    文章目录 前言 原文章 1. Spring Boot 案例 1.1 配置信息 1.2 核心代码 1.2.1 entity 1.2.2 repository 1.2.3 controller 2. Do ...

  8. Spring Boot 2.0(五):Docker Compose + Spring Boot + Nginx + Mysql 实践

    我知道大家这段时间看了我写关于 docker 相关的几篇文章,不疼不痒的,仍然没有感受 docker 的便利,是的,我也是这样认为的,I know your felling . 前期了解概念什么的确实 ...

  9. Spring Boot定时任务应用实践

    在Spring Boot中实现定时任务功能,可以通过Spring自带的定时任务调度,也可以通过集成经典开源组件Quartz实现任务调度. 一.Spring定时器 1.cron表达式方式 使用自带的定时 ...

最新文章

  1. 人类的思维方式有哪些?【达克效应】
  2. 应用进退法确定一维搜索区间_NMR-如何确定官能团含量(MestReC)
  3. java中的深浅拷贝
  4. 大数据hadoop资源网址
  5. linux磁盘使用情况脚本,技术|用 Linux Shell 脚本来监控磁盘使用情况并发送邮件...
  6. 怎样去掉桌面图标和字的蓝色阴影
  7. 【牛客 - 331E】炫酷划线(权值线段树,树状数组哈希,随机数)
  8. 公司有内部推荐的名额
  9. [jquery]高级篇--获取div子元素
  10. jquery-validate 表单验证插件的使用
  11. petalinux笔记
  12. QT 以资源管理器打开文件夹
  13. 鸿蒙手机电脑无缝对接,万物互联?华为鸿蒙OS超级终端功能曝光可一键连接附近设备...
  14. Python123 练习1
  15. UITableView 部分方法详解
  16. 智能合约审计之DDOS概述
  17. 河面上的月亮倒影动画特效
  18. 麦克斯韦方程组在电力传动领域的应用(1)
  19. CreateEvent和SetEvent函数
  20. 先进先出SQL Server 语句

热门文章

  1. 详解两种C#自动实现DLL(OCX)控件注册的方法
  2. LINUX考证优惠信息转发(图)
  3. ibatis+Castle.MCV 版 NPetshop3
  4. 你不知道的 20+ Chrome Devtools 技巧!
  5. 私有云办公平台大规模集群/企业级集群/小型工作室集群解决方案:NextCloud集群部署方案--NextCloud集群架构设计
  6. PPTV Docker集群的网络方案选型
  7. php 字符串混合分割并存入数组
  8. 【JAVA 第四章 流程控制语句】课后习题 直线斜率 以及判断坐标是否在直线上点到直线的距离
  9. C#LeetCode刷题之#453-最小移动次数使数组元素相等(Minimum Moves to Equal Array Elements)
  10. C#算法设计之知识储备