Spring @Async 典型用法

典型用法

⚠️ 注意:@Async 方法不能是 private,也不能在同一个类中直接调用,否则代理失效。

基础用法:异步发送邮件

在配置类上添加 @EnableAsync 来启用异步功能,方法被 @Async 标记后,Spring 会自动将其放入线程池中异步执行。

java 复制代码
// 启用异步支持(必须配置)
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;

@Configuration
@EnableAsync
public class AsyncConfig {
}

--------------------------------------------------------------
// 异步发送邮件
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class EmailService {

    @Async
    public void sendEmail(String to, String content) {
        // 模拟耗时操作
        System.out.println("正在异步发送邮件给:" + to);
        try {
            Thread.sleep(1000); // 模拟发送耗时
        } catch (InterruptedException e) {
            Thread.currentThread().interrupt();
        }
    }
}

自定义线程池(推荐做法)

默认使用的是 Spring 的简单线程池,建议自定义以提高性能和可控性。

java 复制代码
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
public class CustomAsyncConfig {

    @Bean(name = "emailTaskExecutor")
    public Executor emailTaskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(100);
        executor.setThreadNamePrefix("Email-Async-");
        executor.initialize();
        return executor;
    }
}

然后在服务中指定使用该线程池:

java 复制代码
@Async("emailTaskExecutor")
public void sendEmail(String to, String content) {
    // 发送逻辑
}

异常处理(推荐封装)

异步方法中的异常不会直接抛出到主线程,需手动捕获或使用 try-catch 处理,也可以结合 @ControllerAdvice 或日志框架统一处理。

java 复制代码
@Async
public void doSomething() {
    try {
        // 执行任务
    } catch (Exception e) {
        // 记录日志或上报监控
        System.err.println("异步任务发生异常:" + e.getMessage());
    }
}

返回值类型支持

java 复制代码
// void 类型(无返回值)
@Async
public void logAccess(String user) {
    // 记录用户访问日志
}

//  Future / CompletableFuture(有返回值)
@Async
public Future<String> fetchData() {
    String result = "数据加载完成";
    return new AsyncResult<>(result);
}
相关推荐
隔窗听雨眠14 分钟前
openGauss开源五年的内核演进与生态工程
数据库·opengauss·国产数据库
Decay__30 分钟前
PostgreSQL 体系架构全解 —— 进程模型、共享内存、MVCC 与 WAL 预写日志深入
运维·数据库·sql·mysql·架构
码云社区1 小时前
Java在线租房系统源码:VR看房素材、房源图片与内容维护方案
java·vue.js·vr·租房小程序·在线租房·看房租房
码云社区1 小时前
Spring Boot智慧物业系统源码:合同到期提醒、续签资料与资产协作
java·spring boot·后端·物业管理·物业系统·智慧物业
AI开源软件2 小时前
Vue3+SpringBoot3 业务配置统一管理:接管、保存与回退怎样保留有效值
java·前端·vue.js·spring boot·vue·ruoyi office
陈如水2 小时前
Spring AI Alibaba 在多 Agent 场景下的实践
java·人工智能·spring
沐知全栈开发2 小时前
基于ClinicalTrials公开数据的临床试验分析系统-毕业设计
数据库·课程设计
半杯咖啡半行码2 小时前
Qt 隐式共享(Implicit Sharing)深度解析:机制、陷阱与 Qt6迁移
开发语言·数据库·qt
Nturmoils2 小时前
空值、日期、字符串:业务 SQL 里的函数先跑一遍
数据库
吃我一窝jio3 小时前
Docker+Jenkins+K8s全流程部署
java·开发语言·笔记·python