详解Spring Boot 异步执行方法

 更新时间:2018年03月27日 16:54:16   作者:Simeone_xu  
这篇文章主要介绍了Spring Boot 异步执行方法,小编觉得挺不错的,现在分享给大家,也给大家做个参考。一起跟随小编过来看看吧

最近遇到一个需求,就是当服务器接到请求并不需要任务执行完成才返回结果,可以立即返回结果,让任务异步的去执行。开始考虑是直接启一个新的线程去执行任务或者把任务提交到一个线程池去执行,这两种方法都是可以的。但是 Spring 这么强大,肯定有什么更简单的方法,就 google 了一下,还真有呢。就是使用 @EnableAsync 和 @Async 这两个注解就 ok 了。

给方法加上 @Async 注解

package me.deweixu.aysncdemo.service;

public interface AsyncService {

 void asyncMethod(String arg);
}

package me.deweixu.aysncdemo.service.ipml;

import me.deweixu.aysncdemo.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncServiceImpl implements AsyncService {

 @Async
 @Override
 public void asyncMethod(String arg) {
  System.out.println("arg:" + arg);
  System.out.println("=====" + Thread.currentThread().getName() + "=========");
 }
}

@EnableAsync

在启动类或者配置类加上 @EnableAsync 注解

package me.deweixu.aysncdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
public class AysncDemoApplication {

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

测试

package me.deweixu.aysncdemo;

import me.deweixu.aysncdemo.service.AsyncService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AysncDemoApplicationTests {

 @Autowired
 AsyncService asyncService;

 @Test
 public void testAsync() {
  System.out.println("=====" + Thread.currentThread().getName() + "=========");
  asyncService.asyncMethod("Async");
 }

}

=====main=========
2018-03-25 21:30:31.391  INFO 28742 --- [           main] .s.a.AnnotationAsyncExecutionInterceptor : No task executor bean found for async processing: no bean of type TaskExecutor and no bean named 'taskExecutor' either
arg:Async
=====SimpleAsyncTaskExecutor-1=========

从上面的结果看 asyncService.asyncMethod("Async") 确实异步执行了,它使用了一个新的线程。

指定 Executor

从上面执行的日志可以猜测到 Spring 默认使用 SimpleAsyncTaskExecutor 来异步执行任务的,可以搜索到这个类。@Async 也可以指定自定义的 Executor。

在启动类中增加自定义的 Executor

package me.deweixu.aysncdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@EnableAsync
@SpringBootApplication
public class AysncDemoApplication {

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

 @Bean(name = "threadPoolTaskExecutor")
 public Executor threadPoolTaskExecutor() {
  return new ThreadPoolTaskExecutor();
 }
}

指定 Executor

package me.deweixu.aysncdemo.service.ipml;
import me.deweixu.aysncdemo.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncServiceImpl implements AsyncService {

 @Async("threadPoolTaskExecutor")
 @Override
 public void asyncMethod(String arg) {
  System.out.println("arg:" + arg);
  System.out.println("=====" + Thread.currentThread().getName() + "=========");
 }
}

这样在异步执行任务的时候就使用 threadPoolTaskExecutor

设置默认的 Executor

上面提到如果 @Async 不指定 Executor 就默认使用 SimpleAsyncTaskExecutor,其实默认的 Executor 是可以使用 AsyncConfigurer 接口来配置的

@Configuration
public class SpringAsyncConfig implements AsyncConfigurer {  
 @Override
 public Executor getAsyncExecutor() {
  return new ThreadPoolTaskExecutor();
 }  
}

异常捕获

在异步执行的方法中是可能出现异常的,我们可以在任务内部使用 try catch 来处理异常,当任务抛出异常时,Spring 也提供了捕获它的方法。

实现 AsyncUncaughtExceptionHandler 接口

public class CustomAsyncExceptionHandler
 implements AsyncUncaughtExceptionHandler {
 
 @Override
 public 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);
  }
 }  
}

实现 AsyncConfigurer 接口重写 getAsyncUncaughtExceptionHandler 方法

@Configuration
public class SpringAsyncConfig implements AsyncConfigurer {
  
 @Override
 public Executor getAsyncExecutor() {
  return new ThreadPoolTaskExecutor();
 }
 
 @Override
 public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  return new CustomAsyncExceptionHandler();
 }

  
}

改写 asyncMethod 方法使它抛出异常

 @Async
 @Override
 public void asyncMethod(String arg) {
  System.out.println("arg:" + arg);
  System.out.println("=====" + Thread.currentThread().getName() + "=========");
  throw new NullPointerException();
 }

运行结果:

=====main=========
arg:Async
=====threadPoolTaskExecutor-1=========
Exception message - Async NullPointerException
Method name - asyncMethod
Parameter value - Async

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持脚本之家。

相关文章

  • Spring+SpringMVC+Hibernate项目环境搭建的步骤(图文)

    Spring+SpringMVC+Hibernate项目环境搭建的步骤(图文)

    这篇文章主要介绍了Spring+SpringMVC+Hibernate项目环境搭建的步骤(图文),文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2019-05-05
  • java使用EditText控件时不自动弹出输入法的方法

    java使用EditText控件时不自动弹出输入法的方法

    这篇文章主要介绍了java使用EditText控件时不自动弹出输入法的方法,需要的朋友可以参考下
    2015-03-03
  • Java实现矩阵加减乘除及转制等运算功能示例

    Java实现矩阵加减乘除及转制等运算功能示例

    这篇文章主要介绍了Java实现矩阵加减乘除及转制等运算功能,结合实例形式总结分析了java常见的矩阵运算实现技巧,需要的朋友可以参考下
    2018-01-01
  • 10个SpringBoot参数验证你需要知道的技巧分享

    10个SpringBoot参数验证你需要知道的技巧分享

    参数验证很重要,是平时开发环节中不可少的一部分,那么在Spring Boot应用中如何做好参数校验工作呢,本文提供了10个小技巧,你知道几个呢
    2023-03-03
  • spring boot基于注解的声明式事务配置详解

    spring boot基于注解的声明式事务配置详解

    这篇文章主要介绍了spring boot基于注解的声明式事务配置详解,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
    2021-08-08
  • java WebSocket实现聊天消息推送功能

    java WebSocket实现聊天消息推送功能

    这篇文章主要为大家详细介绍了java WebSocket实现聊天消息推送功能,具有一定的参考价值,感兴趣的小伙伴们可以参考一下
    2018-07-07
  • java中的forkjoin框架的使用

    java中的forkjoin框架的使用

    这篇文章主要介绍了java中的fork join框架的使用,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友们下面随着小编来一起学习学习吧
    2020-03-03
  • Java Synchronized锁失败案例及解决方案

    Java Synchronized锁失败案例及解决方案

    这篇文章主要介绍了Java Synchronized锁失败案例及解决方案,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下
    2020-04-04
  • Java虚拟机启动过程探索

    Java虚拟机启动过程探索

    当我们在编写Java应用的时候,很少会注意Java程序是如何被运行的,如何被操作系统管理和调度的,带着好奇心,探索一下Java虚拟机启动过程
    2022-05-05
  • vue+springboot+shiro+jwt实现登录功能

    vue+springboot+shiro+jwt实现登录功能

    这篇文章主要介绍了vue+springboot+shiro+jwt实现登录功能,本文通过示例代码给大家介绍的非常详细,对大家的学习或工作具有一定的参考借鉴价值,需要的朋友可以参考下
    2022-04-04

最新评论