springboot系列教程(三十二):SpringBoot 教程之处理异步请求

SpringBoot 教程之处理异步请求

@EnableAsync 注解

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

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

更详细的配置说明,可以参考:AsyncConfigurer

@Async 注解

支持的用法

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

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

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

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

与使用 @Scheduled 注释注释的方法不同,这些方法可以指定参数,因为它们在运行时由调用者以"正常"方式调用,而不是由容器管理的调度任务调用。例如,以下代码是 @Async 注解的合法应用:

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

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

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

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

不支持的用法

@Async 不能与生命周期回调一起使用,例如 @PostConstruct

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

java 复制代码
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 属性。以下示例显示了如何执行此操作:

java 复制代码
@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 来处理此类异常。以下示例显示了如何执行此操作:

java 复制代码
public class MyAsyncUncaughtExceptionHandler implements AsyncUncaughtExceptionHandler {

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

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

参考资料

相关推荐
NAGNIP2 小时前
多个 GitHub 账户SSH 密钥配置全攻略
后端
NAGNIP3 小时前
Windows命令行代码自动补全详细步骤
后端
.鸣3 小时前
set和map
java·学习
追逐时光者3 小时前
精选 8 款 .NET 开源、前后端分离的快速开发框架,提高开发生产效率!
后端·.net
ha_lydms3 小时前
5、Spark函数_s/t
java·大数据·python·spark·数据处理·maxcompute·spark 函数
用户47949283569154 小时前
性能提升 4000%!我是如何解决 运营看板 不能跨库&跨库查询慢这个难题的
数据库·后端·postgresql
黄河滴滴4 小时前
java系统变卡变慢的原因是什么?从oom的角度分析
java·开发语言
侠客行03174 小时前
Mybatis二级缓存实现详解
java·mybatis·源码阅读
老华带你飞4 小时前
农产品销售管理|基于java + vue农产品销售管理系统(源码+数据库+文档)
java·开发语言·前端·数据库·vue.js·spring boot·后端
Edward111111115 小时前
tomcat_servlet
java·servlet·tomcat