@Async

Spring框架中的 ​@Async​注解是为了支持异步方法调用而设计的。

异步方法调用是指调用方在发起方法调用后,不需要等待被调用方法的结果返回,而是可以立即继续执行其他任务。这种方式能够提高系统的并发性和响应性,特别适用于一些耗时较长、不需要立即获取结果的操作。

  • 引入相关依赖(pom.xml):
java 复制代码
<dependencies>
    <!--其他依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-web</artifactId>
    </dependency>
    <!--添加以下依赖-->
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-aop</artifactId>
    </dependency>
    <dependency>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-task</artifactId>
    </dependency>
    <!--其他依赖-->
</dependencies>
  • 在启动类上添加@EnableAsync注解,开启异步功能。
java 复制代码
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@SpringBootApplication
@EnableAsync
public class DemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(DemoApplication.class, args);
    }
}
  • 创建一个Service类,在其中定义标有@Async注解的异步方法。
java 复制代码
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MyService {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyService.class);

    @Async
    public void asyncMethod() {
        LOGGER.info("Async method start");
        // 模拟耗时操作
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        LOGGER.info("Async method end");
    }
}
  • 创建一个Controller类,调用异步方法。
java 复制代码
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyController {
    @Autowired
    private MyService myService;

    @GetMapping("/async")
    public String async() {
        myService.asyncMethod();
        return "Async method called";
    }
}

当访问 ​http://localhost:8080/async​时,MyService类中的asyncMethod方法将在独立线程中异步执行,而不会阻塞当前请求线程。在日志中可以看到异步方法的开始和结束输出。

要使@Async注解生效,还需要在配置类中添加@EnableAsync注解,并配置合适的线程池。例如,在Spring Boot中可以通过修改application.properties文件添加以下配置:

java 复制代码
spring.task.execution.pool.core-size=5
spring.task.execution.pool.max-size=10
spring.task.execution.pool.queue-capacity=10000
spring.task.execution.pool.thread-name-prefix=my-async-
相关推荐
MageGojo11 小时前
天气 API 接入实战:基于 ApiZero 实现实时天气、分钟级降水和 15 天预报查询
java·后端·spring·api 接口接入·接口实战
☆cwlulu12 小时前
Linux系统调用与C库I/O的底层奥秘
java·spring boot·spring
IT空门:门主14 小时前
Java AI 开发框架终极对比:Spring AI vs Spring AI Alibaba vs AgentScope-Java
java·人工智能·spring·spring ai·ai alibaba·agentscope-java
zzz_236814 小时前
【Spring】面试突击系列(三):Spring Web MVC 深度解析
前端·spring·面试
biubiubiu070615 小时前
SpringBoot 3.5.4 整合Quartz 定时任务
java·spring boot·spring
用户3983461612016 小时前
Go-Spring 实战第 18 课 —— App 使用:启动、配置与运行期扩展
spring·go
zzz_236817 小时前
【Spring】面试突击系列(一):IoC 与 DI 深度解析
java·spring·面试
RemainderTime17 小时前
Spring Boot脚手架集成 Spring Security实现生产级RBAC鉴权
spring boot·后端·spring
宸津-代码粉碎机17 小时前
Spring AI企业级Agent实战|多工具自动规划+并行调度落地,彻底解决复杂业务AI任务编排问题
java·大数据·人工智能·spring boot·python·spring
lixia0417mul217 小时前
flink接入spring体系
java·spring·flink