使用Spring開(kāi)啟@Async異步方式(javaconfig配置)
Spring開(kāi)啟@Async異步(javaconfig配置)
在Spring中,基于@Async標(biāo)注的方法,稱之為異步方法;這些方法將在執(zhí)行的時(shí)候,將會(huì)在獨(dú)立的線程中被執(zhí)行,調(diào)用者無(wú)需等待它的完成,即可繼續(xù)其他的操作。
應(yīng)用場(chǎng)景
- 某些耗時(shí)較長(zhǎng)的而用戶不需要等待該方法的處理結(jié)果
- 某些耗時(shí)較長(zhǎng)的方法,后面的程序不需要用到這個(gè)方法的處理結(jié)果時(shí)
代碼
創(chuàng)建AsyncTask
/**
* 異步任務(wù)
*
* @author Peng
*/
public class AsyncTask {
@Async
public void doAsyncTask() throws InterruptedException {
// 假設(shè)執(zhí)行一個(gè)很耗時(shí)的任務(wù)
Thread.sleep(10 * 1000);
System.out.println("執(zhí)行完成,我執(zhí)行了10秒");
}
}
創(chuàng)建spring配置AppConfig
/**
* spring 配置
*
* @author Peng
*/
@Configuration
@EnableAsync
public class AppConfig {
/**
* 聲明異步任務(wù)bean
*
* @return
*/
@Bean
public AsyncTask asyncTask() {
return new AsyncTask();
}
}
測(cè)試
/**
* 異步測(cè)試
*
* @author Peng
*/
public class AppTest {
public static void main(String[] args) throws InterruptedException {
ApplicationContext ctx = new AnnotationConfigApplicationContext(AppConfig.class);
AsyncTask task = ctx.getBean(AsyncTask.class);
task.doAsyncTask();
System.out.println("異步任務(wù)調(diào)用成功,返回客戶端執(zhí)行成功,異步任務(wù)繼續(xù)執(zhí)行");
}
}
執(zhí)行結(jié)果
異步任務(wù)調(diào)用成功,返回客戶端執(zhí)行成功,異步任務(wù)繼續(xù)執(zhí)行
執(zhí)行完成,我執(zhí)行了10秒
從結(jié)果可以看出,異步任務(wù)測(cè)試成功!
Spring @Async Demo
模擬一個(gè)業(yè)務(wù)場(chǎng)景:系統(tǒng)新用戶注冊(cè)成功后,異步發(fā)送郵件。
Project Directory

Maven Dependency
<?xml version="1.0" encoding="UTF-8"?>
<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
<modelVersion>4.0.0</modelVersion>
<groupId>org.fool.springasync</groupId>
<artifactId>springasync</artifactId>
<name>springasync</name>
<packaging>war</packaging>
<version>1.0.0-BUILD-SNAPSHOT</version>
<properties>
<org.springframework-version>4.2.8.RELEASE</org.springframework-version>
</properties>
<dependencies>
<!-- Spring -->
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-context</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>org.springframework</groupId>
<artifactId>spring-webmvc</artifactId>
<version>${org.springframework-version}</version>
</dependency>
<dependency>
<groupId>com.fasterxml.jackson.core</groupId>
<artifactId>jackson-databind</artifactId>
<version>2.8.1</version>
</dependency>
<dependency>
<groupId>com.google.guava</groupId>
<artifactId>guava</artifactId>
<version>19.0</version>
</dependency>
<dependency>
<groupId>org.apache.commons</groupId>
<artifactId>commons-lang3</artifactId>
<version>3.4</version>
</dependency>
<!-- @Inject -->
<dependency>
<groupId>javax.inject</groupId>
<artifactId>javax.inject</artifactId>
<version>1</version>
</dependency>
<!-- Servlet -->
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>javax.servlet-api</artifactId>
<version>3.1.0</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet.jsp</groupId>
<artifactId>javax.servlet.jsp-api</artifactId>
<version>2.3.1</version>
<scope>provided</scope>
</dependency>
<dependency>
<groupId>javax.servlet</groupId>
<artifactId>jstl</artifactId>
<version>1.2</version>
</dependency>
<!-- Test -->
<dependency>
<groupId>junit</groupId>
<artifactId>junit</artifactId>
<version>4.12</version>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-eclipse-plugin</artifactId>
<version>2.10</version>
<configuration>
<additionalProjectnatures>
<projectnature>org.springframework.ide.eclipse.core.springnature</projectnature>
</additionalProjectnatures>
<additionalBuildcommands>
<buildcommand>org.springframework.ide.eclipse.core.springbuilder</buildcommand>
</additionalBuildcommands>
<downloadSources>true</downloadSources>
<downloadJavadocs>true</downloadJavadocs>
</configuration>
</plugin>
<plugin>
<groupId>org.apache.maven.plugins</groupId>
<artifactId>maven-compiler-plugin</artifactId>
<version>3.5.1</version>
<configuration>
<source>1.8</source>
<target>1.8</target>
<compilerArgument>-Xlint:all</compilerArgument>
<showWarnings>true</showWarnings>
<showDeprecation>true</showDeprecation>
</configuration>
</plugin>
<plugin>
<groupId>org.eclipse.jetty</groupId>
<artifactId>jetty-maven-plugin</artifactId>
<version>9.3.11.v20160721</version>
<configuration>
<scanIntervalSeconds>10</scanIntervalSeconds>
<httpConnector>
<port>8888</port>
</httpConnector>
<webApp>
<contextPath>/springasync</contextPath>
</webApp>
</configuration>
</plugin>
</plugins>
</build>
</project>
web.xml
<?xml version="1.0" encoding="UTF-8"?> <web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_3_0.xsd" id="WebApp_ID" version="3.0"> <!-- The definition of the Root Spring Container shared by all Servlets and Filters --> <context-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/root-context.xml</param-value> </context-param> <!-- Creates the Spring Container shared by all Servlets and Filters --> <listener> <listener-class>org.springframework.web.context.ContextLoaderListener</listener-class> </listener> <!-- Processes application requests --> <servlet> <servlet-name>appServlet</servlet-name> <servlet-class>org.springframework.web.servlet.DispatcherServlet</servlet-class> <init-param> <param-name>contextConfigLocation</param-name> <param-value>/WEB-INF/spring/appServlet/servlet-context.xml</param-value> </init-param> <load-on-startup>1</load-on-startup> </servlet> <servlet-mapping> <servlet-name>appServlet</servlet-name> <url-pattern>/</url-pattern> </servlet-mapping> </web-app>
root-context.xml
<?xml version="1.0" encoding="UTF-8"?> <beans xmlns="http://www.springframework.org/schema/beans" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd"> <!-- Root Context: defines shared resources visible to all other web components --> </beans>
servlet-context.xml
<?xml version="1.0" encoding="UTF-8"?>
<beans:beans xmlns="http://www.springframework.org/schema/mvc" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
xmlns:beans="http://www.springframework.org/schema/beans" xmlns:context="http://www.springframework.org/schema/context"
xmlns:task="http://www.springframework.org/schema/task"
xsi:schemaLocation="http://www.springframework.org/schema/mvc http://www.springframework.org/schema/mvc/spring-mvc.xsd
http://www.springframework.org/schema/beans http://www.springframework.org/schema/beans/spring-beans.xsd
http://www.springframework.org/schema/context http://www.springframework.org/schema/context/spring-context.xsd
http://www.springframework.org/schema/task http://www.springframework.org/schema/task/spring-task.xsd">
<!-- DispatcherServlet Context: defines this servlet's request-processing infrastructure -->
<!-- Enables the Spring MVC @Controller programming model -->
<annotation-driven />
<!-- Handles HTTP GET requests for /resources/** by efficiently serving up static resources in the ${webappRoot}/resources
directory -->
<resources mapping="/resources/**" location="/resources/" />
<!-- Resolves views selected for rendering by @Controllers to .jsp resources in the /WEB-INF/views directory -->
<beans:bean class="org.springframework.web.servlet.view.InternalResourceViewResolver">
<beans:property name="prefix" value="/WEB-INF/views/" />
<beans:property name="suffix" value=".jsp" />
</beans:bean>
<context:component-scan base-package="org.fool.springasync" />
</beans:beans>
AsyncConfig.java
package org.fool.springasync;
import java.util.concurrent.Executor;
import java.util.concurrent.ThreadPoolExecutor;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import org.springframework.context.support.PropertySourcesPlaceholderConfigurer;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
@Configuration
@EnableAsync
@PropertySource("classpath:async.properties")
public class AsyncConfig {
/** Set the ThreadPoolExecutor's core pool size. */
@Value("${core.pool.size}")
private Integer corePoolSize;
/** Set the ThreadPoolExecutor's maximum pool size. */
@Value("${max.pool.size}")
private Integer maxPoolSize;
/** Set the capacity for the ThreadPoolExecutor's BlockingQueue. */
@Value("${queue.capacity}")
private Integer queueCapacity;
@Value("${thread.name.prefix}")
private String ThreadNamePrefix;
@Bean
public static PropertySourcesPlaceholderConfigurer propertySourcesPlaceholderConfig() {
return new PropertySourcesPlaceholderConfigurer();
}
@Bean
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(corePoolSize);
executor.setMaxPoolSize(maxPoolSize);
executor.setQueueCapacity(queueCapacity);
executor.setThreadNamePrefix(ThreadNamePrefix);
// rejection-policy:當(dāng)pool已經(jīng)達(dá)到max size的時(shí)候,如何處理新任務(wù)
// CALLER_RUNS:不在新線程中執(zhí)行任務(wù),而是有調(diào)用者所在的線程來(lái)執(zhí)行
executor.setRejectedExecutionHandler(new ThreadPoolExecutor.CallerRunsPolicy());
executor.initialize();
return executor;
}
}
Note:
AsyncConfig使用Annotation進(jìn)行Spring Async的配置,當(dāng)然也可以用XML的方式進(jìn)行配置,只需要在servlet-context.xml中添加task的命名空間,同時(shí)加下如下兩行配置:
<!-- Enables Spring Async --> <task:annotation-driven executor="asyncExecutor"/> <task:executor id="asyncExecutor" pool-size="2-4" queue-capacity="10"/>
<task:executor />配置參數(shù):
id:當(dāng)配置多個(gè)executor時(shí),被@Async("id")指定使用;也被作為線程名的前綴。
pool-size:
- core size:最小的線程數(shù),缺?。?
- max size:最大的線程數(shù),缺?。篒nteger.MAX_VALUE
queue-capacity:當(dāng)最小的線程數(shù)已經(jīng)被占用滿后,新的任務(wù)會(huì)被放進(jìn)queue里面,當(dāng)這個(gè)queue的capacity也被占滿之后,pool里面會(huì)創(chuàng)建新線程處理這個(gè)任務(wù),直到總線程數(shù)達(dá)到了max size,這時(shí)系統(tǒng)會(huì)拒絕這個(gè)任務(wù)并拋出TaskRejectedException異常(缺省配置的情況下,可以通過(guò)rejection-policy來(lái)決定如何處理這種情況)。缺省值為:Integer.MAX_VALUE
keep-alive:超過(guò)core size的那些線程,任務(wù)完成后,再經(jīng)過(guò)這個(gè)時(shí)長(zhǎng)(秒)會(huì)被結(jié)束掉
rejection-policy:當(dāng)pool已經(jīng)達(dá)到max size的時(shí)候,如何處理新任務(wù)
- ABORT(缺?。簰伋鯰askRejectedException異常,然后不執(zhí)行
- DISCARD:不執(zhí)行,也不拋出異常
- DISCARD_OLDEST:丟棄queue中最舊的那個(gè)任務(wù)
- CALLER_RUNS:不在新線程中執(zhí)行任務(wù),而是有調(diào)用者所在的線程來(lái)執(zhí)行
MailService.java
package org.fool.springasync;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Component;
@Component
public class MailService {
@Async
public void sendMail(String username) {
System.out.println("Send Mail initialization...");
System.out.println("Execute method asynchronously - " + Thread.currentThread().getName());
try {
Thread.sleep(5000);
System.out.println("Welcome " + username);
} catch (InterruptedException e) {
e.printStackTrace();
}
System.out.println("Send Mail Async done!!!");
}
}
User.java
package org.fool.springasync;
import org.apache.commons.lang3.builder.ToStringBuilder;
import org.apache.commons.lang3.builder.ToStringStyle;
public class User {
private Long id;
private String username;
private String password;
public User() {
}
public User(Long id, String username, String password) {
this.id = id;
this.username = username;
this.password = password;
}
public Long getId() {
return id;
}
public void setId(Long id) {
this.id = id;
}
public String getUsername() {
return username;
}
public void setUsername(String username) {
this.username = username;
}
public String getPassword() {
return password;
}
public void setPassword(String password) {
this.password = password;
}
@Override
public String toString() {
return ToStringBuilder.reflectionToString(this, ToStringStyle.SHORT_PREFIX_STYLE);
}
}
UserService.java
package org.fool.springasync;
import javax.inject.Inject;
import org.springframework.stereotype.Service;
@Service
public class UserService {
@Inject
private MailService mailService;
public void registerUser(User user) {
System.out.println("insert user to db...");
mailService.sendMail(user.getUsername());
System.out.println("register done, please check the email later!!!");
}
}
UserController.java
package org.fool.springasync;
import javax.inject.Inject;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
@Controller
@RequestMapping("/user")
public class UserController {
@Inject
private UserService userService;
@RequestMapping(value = "/testasync", method = RequestMethod.POST)
@ResponseBody
public User register(@RequestBody User user) {
System.out.println(user);
userService.registerUser(user);
return user;
}
}
Test
http://localhost:8888/springasync/user/testasync
POST請(qǐng)求(send兩次)

Console Output

以上為個(gè)人經(jīng)驗(yàn),希望能給大家一個(gè)參考,也希望大家多多支持腳本之家。
- SpringCloud解決Feign異步回調(diào)問(wèn)題(SpringBoot+Async+Future實(shí)現(xiàn))
- Springboot?配置線程池創(chuàng)建線程及配置?@Async?異步操作線程池詳解
- spring?boot使用@Async注解解決異步多線程入庫(kù)的問(wèn)題
- 詳解springboot通過(guò)Async注解實(shí)現(xiàn)異步任務(wù)及回調(diào)的方法
- Spring Boot之@Async異步線程池示例詳解
- SpringBoot異步使用@Async的原理以及線程池配置詳解
- Spring里的Async注解實(shí)現(xiàn)異步操作的方法步驟
- 詳解Spring/Spring boot異步任務(wù)編程WebAsyncTask
- Spring中使用Async進(jìn)行異步功能開(kāi)發(fā)實(shí)戰(zhàn)示例(大文件上傳為例)
相關(guān)文章
Java如何Mock FileInputStream問(wèn)題
這篇文章主要介紹了Java如何Mock FileInputStream問(wèn)題,具有很好的參考價(jià)值,希望對(duì)大家有所幫助,如有錯(cuò)誤或未考慮完全的地方,望不吝賜教2023-09-09
Spring Boot利用@Async異步調(diào)用:使用Future及定義超時(shí)詳解
這篇文章主要給大家介紹了關(guān)于Spring Boot利用@Async異步調(diào)用:使用Future及定義超時(shí)的相關(guān)資料,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家學(xué)習(xí)或者使用spring boot具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2018-05-05
詳解SpringBoot實(shí)現(xiàn)fastdfs防盜鏈功能的示例代碼
我們可以通過(guò)fastdfs實(shí)現(xiàn)一個(gè)分布式文件系統(tǒng),如果fastdfs部署在外網(wǎng),那么任何一個(gè)人知道了上傳接口,就可以實(shí)現(xiàn)文件的上傳和訪問(wèn)。那么如何阻止他人訪問(wèn)我們fastdfs服務(wù)器上的文件呢?此處就需要使用fastdfs的防盜鏈功能,本文就來(lái)講講如何實(shí)現(xiàn)這一功能2022-10-10
詳解AOP與Filter攔截請(qǐng)求打印日志實(shí)用例子
這篇文章主要介紹了詳解AOP與Filter攔截請(qǐng)求打印日志實(shí)用例子,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2018-09-09
idea如何自動(dòng)生成serialVersionUID
這篇文章主要介紹了idea如何自動(dòng)生成serialVersionUID,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-02-02
Springboot+Jackson自定義注解數(shù)據(jù)脫敏的項(xiàng)目實(shí)踐
數(shù)據(jù)脫敏可以對(duì)敏感數(shù)據(jù)比如 手機(jī)號(hào)、銀行卡號(hào)等信息進(jìn)行轉(zhuǎn)換或者修改,本文主要介紹了Springboot+Jackson?自定義注解數(shù)據(jù)脫敏,對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧2023-08-08

