@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-
相关推荐
xieliyu.2 小时前
【JavaEE进阶】Spring Boot 日志:从 System.out 到 @Slf4j,6 个级别 + 4 类配置一篇讲透
java·spring boot·spring·java-ee·springboot·logback·slf4j
IT_Octopus2 小时前
Apollo 配置中心入门:一所“小学校“读懂 Portal、Meta Server、Config Service
java·后端·spring
ly76896 小时前
Spring Security 过滤器链定制:认证、CORS 与 CSRF 的先后顺序
java·spring boot·spring·spring security·csrf·cors·过滤器链
ly76898 小时前
Kafka 消费者重试与死信:Spring for Apache Kafka 的边界设计
spring·kafka·apache·并发消费·消费者重试·死信主题·位移提交
OxYGC1 天前
Spring 面经系列 · 第 6 篇:Spring MVC 请求全流程、父子容器与零配置原理
java·spring·mvc
小尹哥-程序员1 天前
第9集:Spring AI Advisor链:像Spring MVC拦截器一样优雅
人工智能·spring·mvc
9527!到!1 天前
Springboot @value读取配置参数踩坑&推荐解决方案
java·spring boot·spring
萧瑟余晖1 天前
Spring Data JPA高级特性详解
后端·spring
frjc1 天前
Spring AI 里 ChatClient 和 ChatModel 有什么区别?什么时候该用哪个?
java·开发语言·spring·ai
Pniubi1 天前
事务(Spring&MySQL)
数据库·sql·spring