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

参考资料

相关推荐
不爱编程的小九九10 分钟前
小九源码-springboot097-java付费自习室管理系统
java·开发语言·spring boot
兜兜风d'10 分钟前
Spring Boot 整合 RabbitMQ :四大核心模式解析
spring boot·rabbitmq·java-rabbitmq
独自破碎E32 分钟前
LeetCode 381: O(1) 时间插入、删除和获取随机元素 - 允许重复
java·算法·leetcode
程语有云34 分钟前
生产事故-Caffeine缓存误用之临下班的救赎
java·缓存·caffeine·阻塞·log·生产事故
Miraitowa_cheems1 小时前
LeetCode算法日记 - Day 81: 最大子数组和
java·数据结构·算法·leetcode·决策树·职场和发展·深度优先
CodeCraft Studio1 小时前
国产化Word处理控件Spire.Doc教程:用Java实现TXT文本与Word互转的完整教程
java·c#·word·spire.doc·word文档转换·txt转word·word转txt
AskHarries1 小时前
Toolhub — 一个干净实用的在线工具集合
前端·后端
徐子童1 小时前
数据结构---优先级队列(堆)
java·数据结构·面试题·优先级队列··topk问题
低音钢琴1 小时前
【SpringBoot从初学者到专家的成长20】SpringBoot集成MongoDB:非关系型数据库的探索
spring boot·mongodb·nosql
滑水滑成滑头1 小时前
**标题:发散创新:智能交通系统的深度探究与实现**摘要:本文将详细
java·人工智能·python