@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-
相关推荐
小北方城市网1 小时前
SpringBoot 安全认证实战(Spring Security + JWT):打造无状态安全接口体系
数据库·spring boot·后端·安全·spring·mybatis·restful
小园子的小菜2 小时前
Spring事务失效9大场景(Java面试高频)
java·spring·面试
Remember_9932 小时前
【数据结构】Java数据结构深度解析:栈(Stack)与队列(Queue)完全指南
java·开发语言·数据结构·算法·spring·leetcode·maven
Remember_9933 小时前
深入理解 Java String 类:从基础原理到高级应用
java·开发语言·spring·spring cloud·eclipse·tomcat
马达加斯加D3 小时前
缓存 --- Redis缓存的一致性
分布式·spring·缓存
无名-CODING3 小时前
Spring Bean生命周期详解:从入门到精通
java·后端·spring
卓怡学长4 小时前
m111基于MVC的舞蹈网站的设计与实现
java·前端·数据库·spring boot·spring·mvc
笔墨新城14 小时前
Agent Spring Ai 开发之 (一) 基础配置
人工智能·spring·agent
梁下轻语的秋缘15 小时前
ESP32-WROOM-32E存储全解析:RAM/Flash/SD卡读写与速度对比
java·后端·spring
想用offer打牌18 小时前
Spring AI Alibaba与 Agent Scope到底选哪个?
java·人工智能·spring