两者都是实现Spring容器中实现bean方法的异步调用。
比如有个loginService的bean,loginService中有个log方法用来记录日志,当调用logService.log(msg) 的时候,系统异步执行,可以通过@EnableAsync & @Async来实现。
常见两种用法
无返回值的:
方法返回值不是Futrue类型的,被执行时,会立即返回,并且无法获取方法返回值。
什么是Futrue?
在并发编程中,我们经常用到非阻塞的模型,在之前的多线程的三种实现中,不管是继承thread类还是实现runnable接口,都无法保证获取到之前的执行结果。通过实现Callback接口,并用Future可以来接收多线程的执行结果。
Future表示一个可能还没有完成的异步任务的结果,针对这个结果可以添加Callback以便在任务执行成功或失败后作出相应的操作。
举个例子:比如去吃早点时,点了包子和凉菜,包子需要等3分钟,凉菜只需1分钟,如果是串行的一个执行,在吃上早点的时候需要等待4分钟,但是因为你在等包子的时候,可以同时准备凉菜,所以在准备凉菜的过程中,可以同时准备包子,这样只需要等待3分钟。那Future这种模式就是后面这种执行模式。
用法:
- @Async
- public void log(String msg) throws InterruptedException {
- System.out.println("开始记录日志," + System.currentTimeMillis());
- //模拟耗时2秒
- TimeUnit.SECONDS.sleep(2);
- System.out.println("日志记录完毕," + System.currentTimeMillis());
- }
用法:
若需获取异步执行结果,方法返回值必须为Futrue类型,使用spring提供的静态方法。
- public Future
getGoodsInfo(long goodsId) throws InterruptedException { - return AsyncResult.forValue(String.format("商品%s基本信息!", goodsId));
- }
举例:
- @Async
- @Component
- public class GoodsService {
- //模拟获取商品基本信息,内部耗时500毫秒
- public Future
getGoodsInfo(long goodsId) throws InterruptedException { - TimeUnit.MILLISECONDS.sleep(500);
- return AsyncResult.forValue(String.format("商品%s基本信息!", goodsId));
- }
- //模拟获取商品描述信息,内部耗时500毫秒
- public Future
getGoodsDesc(long goodsId) throws InterruptedException { - TimeUnit.MILLISECONDS.sleep(500);
- return AsyncResult.forValue(String.format("商品%s描述信息!", goodsId));
- }
- //模拟获取商品评论信息列表,内部耗时500毫秒
- public Future
> getGoodsComments(long goodsId) throws InterruptedException {
- TimeUnit.MILLISECONDS.sleep(500);
- List
comments = Arrays.asList("评论1", "评论2"); - return AsyncResult.forValue(comments);
- }
- }
- @Component
- @EnableAsync
- public class MainConfig {
- }
- @Test
- public void test() throws InterruptedException, ExecutionException {
- AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext();
- context.register(MainConfig.class);
- context.refresh();
- GoodsService goodsService = context.getBean(GoodsService.class);
- long starTime = System.currentTimeMillis();
- System.out.println("开始获取商品的各种信息");
- long goodsId = 1L;
- Future
goodsInfoFuture = goodsService.getGoodsInfo(goodsId); - Future
goodsDescFuture = goodsService.getGoodsDesc(goodsId); - Future
> goodsCommentsFuture = goodsService.getGoodsComments(goodsId);
- System.out.println(goodsInfoFuture.get());
- System.out.println(goodsDescFuture.get());
- System.out.println(goodsCommentsFuture.get());
- System.out.println("商品信息获取完毕,总耗时(ms):" + (System.currentTimeMillis() - starTime));
- //休眠一下,防止@Test退出
- TimeUnit.SECONDS.sleep(3);
- }
执行结果:
开始获取商品的各种信息商品 1 基本信息 !商品 1 描述信息 ![ 评论 1 , 评论 2 ]商品信息获取完毕 , 总耗时 ( ms ) : 525
3个方法总计耗时500毫秒左右。 如果不采用异步的方式,3个方法会同步执行,耗时差不多1.5秒。按照这个思路可以去优化一下你们的代码,方法之间无关联的可以采用异 步的方式,并行去获取,最终耗时为最长的那个方法,整体相对于同步的方式性能提升不少。
- @Bean
- public Executor taskExecutor() {
- ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
- executor.setCorePoolSize(10);
- executor.setMaxPoolSize(100);
- executor.setThreadNamePrefix("my-thread-");
- return executor;
- }
方式二:定义一个bean,实现AsyncConfigurer接口中的getAsyncExecutor方法,这个方法需要返回自定义的线程池。
异步方法出现了异常,我们可以通过自定义异常处理来解决。
两种情况:
- //情况1
- try {
- Future
future = logService.mockException(); - System.out.println(future.get());
- } catch (ExecutionException e) {
- System.out.println("捕获 ExecutionException 异常");
- //通过e.getCause获取实际的异常信息
- e.getCause().printStackTrace();
- } catch (InterruptedException e) {
- e.printStackTrace();
- }
- //情况2
- @Bean
- public AsyncConfigurer asyncConfigurer() {
- return new AsyncConfigurer() {
- @Nullable
- @Override
- public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
- return new AsyncUncaughtExceptionHandler() {
- @Override
- public void handleUncaughtException(Throwable ex, Method method, Object... params) {
- //当目标方法执行过程中抛出异常的时候,此时会自动回调这个方法,可以在这个方法中处理异常
- }
- };
- }
- };
- }
什么是线程池隔离?
一个系统中可能有很多业务,比如重置服务、提现服务或者其他服务,这些服务中都有一些方法需要异步执行,默认情况下他们会使用同一个线程池去执行,如果有一个业务量比较大,占用了线程池中的大量线程,此时会导致其他业务的方法无法执行,那么我们可以采用线程隔离的方式,对不同的业务使用不同的线程池,相互隔离,互不影响。
- @Component
- public class RechargeService {
- //模拟异步充值
- @Async(MainConfig.RECHARGE_EXECUTORS_BEAN_NAME)
- public void recharge() {
- System.out.println(Thread.currentThread() + "模拟异步充值");
- }
- }
内部使用AOp实现的,@EnableAsync会引入一个bean后置处理器:
AsyncAnnotationBeanPostProcessor ,将其注册到Spring容器,这个bean后置处理器在所有bean创 建过程中,判断bean的类上是否有@Async注解或者类中是否有@Async标注的方法,如果有,会通过aop给这个bean生成代理对象,会在代理对象中添加一个切面:org.springframework.scheduling.annotation.AsyncAnnotationAdvisor,这个切面中会引入一个拦截器:AnnotationAsyncExecutionInterceptor,方法异步调用的关键代码就是在这个拦截器的invoke方法中实现的。
