成人免费xxxxx在线视频软件_久久精品久久久_亚洲国产精品久久久_天天色天天色_亚洲人成一区_欧美一级欧美三级在线观看

異步處理:Spring @Async 注解深度剖析!

開發
Spring @Async 注解提供了一個非常簡單而且強大的機制來支持異步方法的執行。這篇文章,我們來深度剖析 Spring @Async 的工作原理!

Spring @Async 注解提供了一個非常簡單而且強大的機制來支持異步方法的執行。如果將方法標記為@Async,Spring會在后臺線程中異步執行該方法,而不會阻塞調用該方法的線程。這對于提高應用程序的響應性和性能是非常有用的,尤其是在處理I/O密集型操作時。這篇文章,我們來深度剖析 Spring @Async 的工作原理!

1. 原理概述

使用@Async注解時,Spring 借助 AOP(面向切面編程)實現異步執行,具體來說,@Async的工作原理主要包括以下幾個步驟:

  • 代理對象創建:Spring 使用動態代理創建被注解方法的代理對象。只有與代理對象交互時,@Async 注解才會起作用。
  • 線程池配置:異步方法調用通過 Spring 提供的 TaskExecutor(如 SimpleAsyncTaskExecutor, ThreadPoolTaskExecutor 等)來實現多線程處理。開發者可以自定義線程池設置,以適應不同的使用場景。
  • 方法執行:當調用被 @Async 注解的方法時,Spring 將檢測到這個注解,然后將方法的調用委托給一個線程池中的線程。在這個線程執行完成后,控制權就會返回到調用線程,不會被阻塞。

2. 核心代碼分析

下面我們深入探討@Async的幾個核心類的實現細節。

(1) @Async 注解

@Async注解的定義非常簡單,位于org.springframework.scheduling.annotation包中:

@Target(ElementType.METHOD)
@Retention(RetentionPolicy.RUNTIME)
public @interface Async {
    String value() default "";
}

通過上面的源碼可以看出:@Async注解只支持放在方法上,并可以指定一個可選的線程池名稱。

(2) AsyncConfiguration類

要啟用異步處理功能,我們需要有一個配置類或在Spring Boot應用程序中使用@EnableAsync注解。這個注解會觸發 Spring的異步支持機制。

@Configuration
@EnableAsync
public class AsyncConfig extends AsyncConfigurerSupport {
    @Override
    public Executor getAsyncExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(5);
        executor.setMaxPoolSize(10);
        executor.setQueueCapacity(25);
        executor.initialize();
        return executor;
    }
}

在這個示例中,我們擴展了AsyncConfigurerSupport類,并重寫了getAsyncExecutor方法來提供自定義的線程池。

(3) Proxy 生成

Spring 通過 AOP 動態代理機制處理 @Async 注解。具體過程如下:

  • Spring 在創建代理對象時,檢查被注解的方法。
  • 如果發現方法上有 @Async 注解,Spring 將為這個方法生成一個增強版本,以確保調用被轉發到線程池中的一個工作線程。

通常,Spring 會使用 JDK 動態代理或者 CGLIB 代理。JDK 代理基于接口創建代理實例,而 CGLIB 可以基于類創建代理實例。

(4) 異步方法的調用

以下是 @Async 方法的簡單示例:

@Service
public class MyAsyncService {
    @Async
    public void asyncMethod() {
        System.out.println("Executing in " + Thread.currentThread().getName());
    }
}

調用 asyncMethod() 方法時,控制將立即返回,不會阻塞。實際方法將在其他線程中執行。

(5) AsyncExecutionInterceptor

AsyncExecutionInterceptor 類是 Spring 處理異步執行的核心部分。它實現了 MethodInterceptor 接口,能夠攔截方法調用,進行異步執行處理。

public class AsyncExecutionInterceptor extends AbstractAsyncExecutionInterceptor {
    @Override
    public Object invoke(MethodInvocation invocation) throws Throwable {
        return doInvoke(invocation);
    }
}

在 invoke 方法中,doInvoke 方法會被調用,負責具體的執行邏輯。

3.示例

為了更好地理解 @Async 的使用,我們通過一個完整的示例來演示如何使用 Spring @Async 注解實現異步方法調用,示例將包含以下部分:

  • Spring Boot 項目結構。
  • @Async 注解的實現和配置。
  • 異步方法的調用示例。
  • 運行時的輸出示例。

(1) 創建 Spring Boot 項目

假設你使用 Spring Boot 創建項目,可以創建一個新的 Gradle 或 Maven 項目,添加以下依賴項到 pom.xml(如果使用 Maven):

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter</artifactId>
</dependency>
<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>

(2) 配置異步支持

創建一個配置類來啟用異步支持,使用 @EnableAsync 注解。

import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;

import java.util.concurrent.Executor;

@Configuration
@EnableAsync
public class AsyncConfig {
    
    @Bean(name = "taskExecutor")
    public Executor taskExecutor() {
        ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
        executor.setCorePoolSize(2);
        executor.setMaxPoolSize(5);
        executor.setQueueCapacity(10);
        executor.setThreadNamePrefix("Async-");
        executor.initialize();
        return executor;
    }
}

(3) 創建異步服務類

接下來,創建一個服務類,其中將包含異步方法。該方法將模擬一些耗時的操作。

import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class MyAsyncService {

    @Async("taskExecutor")
    public void asyncMethod() {
        System.out.println("Executing async method: " + Thread.currentThread().getName());
        try {
            // 模擬耗時的操作
            Thread.sleep(3000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.out.println("Async method execution finished: " + Thread.currentThread().getName());
    }
}

(4) 創建控制器類

創建一個控制器類,調用異步服務中的方法:

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
public class MyAsyncController {

    @Autowired
    private MyAsyncService myAsyncService;

    @GetMapping("/asyncTest")
    public String callAsync() {
        System.out.println("Calling async method");
        myAsyncService.asyncMethod();
        return "Async method called!";
    }
}

(5) 主應用程序類

創建 Spring Boot 啟動類,用于啟動應用程序:

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;

@SpringBootApplication
public class AsyncApplication {

    public static void main(String[] args) {
        SpringApplication.run(AsyncApplication.class, args);
    }
}

(6) 運行應用程序

啟動 Spring Boot 應用程序,在瀏覽器中訪問以下 URL:http://localhost:8080/asyncTest

輸出結果為:

Calling async method
Executing async method: Async-1
Async method execution finished: Async-1

在瀏覽器中,頁面將返回 “Async method called!” 的信息,而不會等待 asyncMethod 完成執行。這表示 asyncMethod 在另一個線程上異步執行。

4. 總結

通過以上分析,我們可以看到 Spring 的@Async提供了異步編程的簡便機制。它的實現依賴于 AOP代理,以及可配置的線程池。透過這些機制,Spring 能夠將對異步方法的調用轉發到后臺線程中執行,同時保證主線程不會被阻塞。

責任編輯:趙寧寧 來源: 猿java
相關推薦

2024-06-13 00:54:19

2024-12-24 14:01:10

2021-08-04 17:20:30

阿里巴巴AsyncJava

2024-05-07 08:23:03

Spring@Async配置

2024-08-22 10:39:50

@Async注解代理

2025-04-08 00:00:00

@AsyncSpring異步

2018-09-18 16:20:08

Asyncjavascript前端

2017-04-19 08:47:42

AsyncJavascript異步代碼

2024-12-23 08:00:45

2018-06-21 14:46:03

Spring Boot異步調用

2022-09-27 18:56:28

ArrayList數組源代碼

2024-02-05 19:06:04

DartVMGC流程

2025-06-04 08:30:00

seata分布式事務開發

2024-07-12 14:46:20

2010-01-13 13:42:55

C++編譯器

2024-07-11 08:17:00

2021-11-11 15:25:28

@AsyncJava線程池

2025-01-08 10:35:26

代碼開發者Spring

2024-03-28 12:51:00

Spring異步多線程

2021-03-29 09:26:44

SpringBoot異步調用@Async
點贊
收藏

51CTO技術棧公眾號

主站蜘蛛池模板: 性一交一乱一伦视频免费观看 | 日日夜夜草 | 欧美三区| 中文字幕日韩欧美 | 国产成人精品综合 | 一级毛片大全免费播放 | 久草99 | 日韩网站在线观看 | 欧美一区二区三区在线观看视频 | 日韩欧美在线免费观看 | 国产不卡在线观看 | 成人精品国产 | 中文字幕国产 | 国产最好的av国产大片 | 狠狠色综合久久丁香婷婷 | 黄免费观看视频 | 日韩字幕一区 | 欧美日韩综合视频 | 国产精品免费一区二区三区 | 久久久久久亚洲 | 欧美精品一区二区三区四区 在线 | 成人av一区 | 国产一区亚洲二区三区 | 久久亚洲精品国产精品紫薇 | xxx国产精品视频 | 国产午夜精品一区二区三区 | 日本一区二区高清不卡 | 成人欧美在线 | 亚洲成人精品 | 亚洲精品一区二区 | 亚洲国产aⅴ成人精品无吗 国产精品永久在线观看 | 91精品国产自产精品男人的天堂 | 国产精品久久久久久久久久久久久久 | 欧美黑人国产人伦爽爽爽 | 午夜免费av| 看片wwwwwwwwwww | 美女国产一区 | 久久久91 | 欧美 日韩精品 | 国产精品久久久久久久久久 | 在线观看av网站永久 |