在Java中使用Spring Boot實現異步請求和異步調用是一個常見的需求,可以提高應用程序的性能和響應能力。以下是實現這兩種異步操作的基本方法:
一、異步請求(Asynchronous Request)
異步請求允許客戶端發送請求后立即返回,而不需要等待服務器處理完成,異步調用允許在服務端異步執行方法,不阻塞主線程。
二、在 Spring Boot 中,實現異步調用主要有以下幾種方法:
1. 使用 @Async 注解
步驟:
- 啟用異步支持:在主類上添加
@EnableAsync
。 - 定義異步方法:在需要異步執行的方法上使用
@Async
注解。 - 自定義線程池(可選):提高異步任務的線程管理效率,以便異步方法能夠在獨立的線程中執行
示例代碼:
主類:
package com.work;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;
@SpringBootApplication(scanBasePackages = {"com.work.*"})
@EnableAsync
//@EnableScheduling
public class SpringBootWorkApplication {public static void main(String[] args) {SpringApplication.run(SpringBootWorkApplication.class, args);}
}
異步方法:
package com.work.service;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
/*** 異步調用service* @author summer*/
@Service
@Slf4j
public class AsyncService {/*** 使用 @Async 注解 實現異步調用* taskExecutor為自定義線程池,指定自定義線程池* @return* @throws InterruptedException*/@Async("taskExecutor")public void async(){log.info("async異步任務開始: " + Thread.currentThread().getName());try {// 模擬耗時操作(實際工作中,此處寫業務邏輯處理) Thread.sleep(30000); } catch (InterruptedException e) {e.printStackTrace();}log.info("async異步任務完成");}
}
自定義線程池(可選):
package com.work.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/*** 自定義異步線程執行線程池* @author summer**/
@Configuration
public class ExecutorConfig {@Bean(name = "taskExecutor")public TaskExecutor taskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.setQueueCapacity(50);executor.setThreadNamePrefix("TaskExecutor-");executor.initialize();return executor;}
}
在 @Async("taskExecutor")
中指定自定義線程池。
調用:
package com.work.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.work.common.result.CommonResult;
import com.work.service.AsyncService;
import lombok.extern.slf4j.Slf4j;/*** 測試異步執行Controller* @author summer**/
@RestController
@RequestMapping("/async")
@Slf4j
public class AsyncTestController {@Autowiredprivate AsyncService asyncService;@GetMapping("/async")public CommonResult<String> async() {asyncService.async();log.info("async異步任務調用成功");return CommonResult.success("async異步任務調用成功");}
}
異步方法休眠30秒,可以看到控制臺打印的日志
線程池配置建議
- CPU 密集型任務:建議核心線程數為 CPU 核心數的
n
倍,最大線程數為核心線程數的 2 倍。 - IO 密集型任務:建議核心線程數設置為較大的值,最大線程數可以為核心線程數的 2 倍甚至更多。
合理配置線程池可以避免線程饑餓和死鎖等問題,提升系統的吞吐量。
2. 使用 Java 原生線程池
Spring 提供線程池,但可以直接使用 Java 原生的線程池來實現異步。
示例代碼:
package com.work.service;
import java.util.concurrent.LinkedBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;/*** 異步調用service* @author summer**/
@Service
@Slf4j
public class AsyncService{/*** 使用 Java 原生線程池來實現異步調用*/public void asyncThreadPool() {ThreadPoolExecutor pool=new ThreadPoolExecutor(5, 10, 2, TimeUnit.SECONDS, new LinkedBlockingQueue<Runnable>(100),new ThreadPoolExecutor.CallerRunsPolicy());pool.execute(() -> {log.info("asyncThreadPool異步任務開始: " + Thread.currentThread().getName());try {// 模擬耗時操作(實際工作中,此處寫業務邏輯處理) Thread.sleep(30000);} catch (InterruptedException e) {e.printStackTrace();}log.info("asyncThreadPool異步任務完成");});}
}
調用:
package com.work.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.work.common.result.CommonResult;
import com.work.service.AsyncService;
import lombok.extern.slf4j.Slf4j;/*** 測試異步執行Controller* @author summer**/
@RestController
@RequestMapping("/async")
@Slf4j
public class AsyncTestController {@Autowiredprivate AsyncService asyncService;@GetMapping("/asyncThreadPool")public CommonResult<String> asyncThreadPool() {asyncService.asyncThreadPool();log.info("asyncThreadPool異步任務調用成功");return CommonResult.success("asyncThreadPool異步任務調用成功");}
}
異步方法休眠30秒,可以看到控制臺打印的日志
3. 使用 Spring 的 TaskExecutor
TaskExecutor
是 Spring 提供的抽象接口,適合用來執行異步任務。
配置 TaskExecutor:
package com.work.config;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
/*** 自定義異步線程執行線程池* @author summer**/
@Configuration
public class ExecutorConfig {@Bean(name = "taskExecutor")public TaskExecutor taskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(5);executor.setMaxPoolSize(10);executor.setQueueCapacity(50);executor.setThreadNamePrefix("TaskExecutor-");executor.initialize();return executor;}
}
示例代碼:
package com.work.service;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.task.TaskExecutor;
import org.springframework.stereotype.Service;
import lombok.extern.slf4j.Slf4j;
/*** 異步調用service* @author summer**/
@Service
@Slf4j
public class AsyncService{@Autowiredprivate TaskExecutor taskExecutor;/*** 使用 Spring 的 TaskExecutor 來實現異步調用*/public void asyncExecutor() {taskExecutor.execute(() -> {log.info("asyncExecutor異步任務開始:" + Thread.currentThread().getName());try {// 模擬耗時操作(實際工作中,此處寫業務邏輯處理) Thread.sleep(30000);} catch (InterruptedException e) {e.printStackTrace();}log.info("asyncExecutor異步任務完成");});}
}
調用:
package com.work.controller;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import com.work.common.result.CommonResult;
import com.work.service.AsyncService;
import lombok.extern.slf4j.Slf4j;/*** 測試異步執行Controller* @author summer**/
@RestController
@RequestMapping("/async")
@Slf4j
public class AsyncTestController {@Autowiredprivate AsyncService asyncService;@GetMapping("/asyncExecutor")public CommonResult<String> asyncExecutor() {asyncService.asyncExecutor();log.info("asyncExecutor異步任務調用成功");return CommonResult.success("asyncExecutor異步任務調用成功");}
}
異步方法休眠30秒,可以看到控制臺打印的日志
三、什么時候使用異步請求
異步請求在以下情況下特別有用:
- 長時間運行的任務:例如文件上傳、復雜計算、大量數據處理等。
- I/O操作:例如數據庫查詢、調用外部API、文件讀寫等。
- 資源密集型任務:例如圖像處理、視頻編碼等。
四、總結
方法
優點
缺點
@Async 注解
簡單易用,與 Spring 集成良好
需要 Spring 容器管理的 Bean 才能生效
ExecutorService
更底層、更靈活
手動管理線程池
TaskExecutor
Spring 提供的抽象,方便擴展
配置稍顯復雜
這些示例展示了如何在Spring Boot中實現異步請求和異步調用。Spring Boot提供了`@Async`注解和`Java原生線程池`、`TaskExecutor`來實現這一功能,提高了應用程序的并發處理能力,開發者可以根據不同的需求選擇合適的異步處理方式。
合理配置線程池,以確保最佳性能和資源利用,正確處理異步任務中的異常,以及在合適的場景中應用異步處理技術,是開發高性能應用的關鍵。