SpringBoot 教程之处理异步请求

异步用法

@EnableAsync 注解

要使用 @Async,首先须要使用 @EnableAsync 注解开启 Spring Boot 中的异步特性。html

@Configuration
@EnableAsync
public class AppConfig {
}
复制代码

更详细的配置说明,能够参考:AsyncConfigurerjava

@Async 注解

支持的用法

(1)无入参无返回值方法git

您能够用 @Async 注解修饰方法,这代表这个方法是异步方式调用。换句话说,程序在调用此方法时会当即返回,而方法的实际执行发生在已提交给 Spring TaskExecutor 的任务中。在最简单的状况下,您能够将注解应用于返回 void 的方法,如如下示例所示:github

@Async
void doSomething() {
    // this will be executed asynchronously
}
复制代码

(2)有入参无返回值方法spring

与使用 @Scheduled 注释注释的方法不一样,这些方法能够指定参数,由于它们在运行时由调用者以“正常”方式调用,而不是由容器管理的调度任务调用。例如,如下代码是 @Async 注解的合法应用:api

@Async
void doSomething(String s) {
    // this will be executed asynchronously
}
复制代码

(3)有入参有返回值方法bash

甚至能够异步调用返回值的方法。可是,这些方法须要具备 Future 类型的返回值。这仍然提供了异步执行的好处,以便调用者能够在调用 Future 上的 get() 以前执行其余任务。如下示例显示如何在返回值的方法上使用@Async异步

@Async
Future<String> returnSomething(int i) {
    // this will be executed asynchronously
}
复制代码

不支持的用法

@Async 不能与生命周期回调一块儿使用,例如 @PostConstructasync

要异步初始化 Spring bean,必须使用单独的初始化 Spring bean,而后在目标上调用 @Async 带注释的方法,如如下示例所示:ide

public class SampleBeanImpl implements SampleBean {

    @Async
    void doSomething() {
        // ...
    }

}

public class SampleBeanInitializer {

    private final SampleBean bean;

    public SampleBeanInitializer(SampleBean bean) {
        this.bean = bean;
    }

    @PostConstruct
    public void initialize() {
        bean.doSomething();
    }

}
复制代码

明确指定执行器

默认状况下,在方法上指定 @Async 时,使用的执行器是在启用异步支持时配置的执行器,即若是使用 XML 或 AsyncConfigurer 实现(若是有),则为“annotation-driven”元素。可是,若是须要指示在执行给定方法时应使用默认值之外的执行器,则可使用 @Async 注解的 value 属性。如下示例显示了如何执行此操做:

@Async("otherExecutor")
void doSomething(String s) {
    // this will be executed asynchronously by "otherExecutor"
}
复制代码

在这种状况下,“otherExecutor”能够是 Spring 容器中任何 Executor bean 的名称,也能够是与任何 Executor 关联的限定符的名称(例如,使用 <qualifier> 元素或 Spring 的 @Qualifier 注释指定) )。

管理 @Async 的异常

@Async 方法的返回值类型为 Future 型时,很容易管理在方法执行期间抛出的异常,由于在调用 get 结果时会抛出此异常。可是,对于返回值类型为 void 型的方法,异常不会被捕获且没法传输。您能够提供 AsyncUncaughtExceptionHandler 来处理此类异常。如下示例显示了如何执行此操做:

public class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {

    @Override
    public void handleUncaughtException(Throwable ex, Method method, Object... params) {
        // handle exception
    }
}
复制代码

默认状况下,仅记录异常。您可使用 AsyncConfigurer<task:annotation-driven /> XML元素定义自定义 AsyncUncaughtExceptionHandler

源码

完整示例:源码

使用方法:

mvn clean package
cd target
java -jar sbe-core-asyn.jar
复制代码

引伸和引用

引伸

参考

相关文章
相关标签/搜索