@
例子翻譯自國外的兩篇博客:
實驗環境准備
- JDK 1.8
- SpringBoot2.2.1
- Maven 3.2+
- 開發工具
- IntelliJ IDEA
- smartGit
創建一個SpringBoot Initialize項目,詳情可以參考我之前博客:SpringBoot系列之快速創建項目教程
pom.xml:
<?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 https://maven.apache.org/xsd/maven-4.0.0.xsd">
<modelVersion>4.0.0</modelVersion>
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.2.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<groupId>com.example.springboot</groupId>
<artifactId>springboot-async</artifactId>
<version>0.0.1-SNAPSHOT</version>
<name>springboot-async</name>
<description>Demo project for Spring Boot</description>
<properties>
<java.version>1.8</java.version>
</properties>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<optional>true</optional>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
<exclusions>
<exclusion>
<groupId>org.junit.vintage</groupId>
<artifactId>junit-vintage-engine</artifactId>
</exclusion>
</exclusions>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
</project>
github用戶信息類
@JsonIgnoreProperties(ignoreUnknown = true),將這個注解寫在類上之后,就會忽略類中不存在的字段,可以滿足當前的需要。
package com.example.springboot.async.bean;
import com.fasterxml.jackson.annotation.JsonIgnore;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
import lombok.Data;
import java.io.Serializable;
/**
* <pre>
* 用戶信息實體類
* Copy @ https://spring.io/guides/gs/async-method/
* </pre>
*
* <pre>
* 修改記錄
* 修改后版本: 修改人: 修改日期: 2020/07/20 10:14 修改內容:
* </pre>
*/
@JsonIgnoreProperties(ignoreUnknown = true)
@Data
public class User implements Serializable {
private String name;
private String blog;
@Override
public String toString() {
return "User{" +
"name='" + name + '\'' +
", blog='" + blog + '\'' +
'}';
}
}
異步任務配置類
可以實現AsyncConfigurerSupport 類,也可以使用@Bean(name = "threadPoolTaskExecutor")
的方法,這里定義了線程池的配置
package com.example.springboot.async.config;
import com.example.springboot.async.exception.CustomAsyncExceptionHandler;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.scheduling.annotation.AsyncConfigurer;
import org.springframework.scheduling.annotation.AsyncConfigurerSupport;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
/**
* <pre>
* AsyncConfiguration
* Copy @https://spring.io/guides/gs/async-method/
* </pre>
*
* <pre>
* 修改記錄
* 修改后版本: 修改人: 修改日期: 2020/07/20 10:12 修改內容:
* </pre>
*/
@Configuration
@EnableAsync
public class AsyncConfiguration extends AsyncConfigurerSupport {
@Override
public Executor getAsyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("GithubLookup-");
executor.initialize();
return executor;
}
/*@Bean(name = "threadPoolTaskExecutor")
public Executor threadPoolTaskExecutor() {
return new ThreadPoolTaskExecutor();
}*/
}
查詢github用戶信息業務類
使用Future獲得異步執行結果時,要么調用阻塞方法get(),要么輪詢看isDone()是否為true,這兩種方法都不是很好,因為主線程也會被迫等待。
在Java8中,CompletableFuture提供了非常強大的Future的擴展功能,可以幫助我們簡化異步編程的復雜性,並且提供了函數式編程的能力,可以通過回調的方式處理計算結果,也提供了轉換和組合 CompletableFuture 的方法。
package com.example.springboot.async.service;
import com.example.springboot.async.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.web.client.RestTemplateBuilder;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;
import java.util.concurrent.CompletableFuture;
import java.util.concurrent.Future;
/**
* <pre>
* GitHubLookupService
* copy @https://spring.io/guides/gs/async-method/
* </pre>
*
* <pre>
* 修改記錄
* 修改后版本: 修改人: 修改日期: 2020/07/20 10:18 修改內容:
* </pre>
*/
@Service
public class GitHubLookupService {
private static final Logger LOG = LoggerFactory.getLogger(GitHubLookupService.class);
private final RestTemplate restTemplate;
public GitHubLookupService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
@Async
//@Async("threadPoolTaskExecutor")
public Future<User> findUser(String user) throws InterruptedException {
LOG.info("Looking up " + user);
String url = String.format("https://api.github.com/users/%s", user);
User results = restTemplate.getForObject(url, User.class);
// Artificial delay of 1s for demonstration purposes
Thread.sleep(1000L);
return CompletableFuture.completedFuture(results);
}
}
啟動測試類實現
實現CommandLineRunner 接口,SpringBoot啟動時候,會自動調用,也可以用@Order指定執行順序
package com.example.springboot.async.service;
import com.example.springboot.async.bean.User;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.concurrent.Future;
/**
* <pre>
* CommandLineRunner
* Copy @https://spring.io/guides/gs/async-method/
* </pre>
*
* <pre>
* 修改記錄
* 修改后版本: 修改人: 修改日期: 2020/07/20 10:25 修改內容:
* </pre>
*/
@Component
public class AppRunner implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(AppRunner.class);
@Autowired
GitHubLookupService gitHubLookupService;
@Override
public void run(String... args) throws Exception {
// Start the clock
long start = System.currentTimeMillis();
// Kick of multiple, asynchronous lookups
Future<User> page1 = gitHubLookupService.findUser("PivotalSoftware");
Future<User> page2 = gitHubLookupService.findUser("CloudFoundry");
Future<User> page3 = gitHubLookupService.findUser("Spring-Projects");
// Wait until they are all done
while (!(page1.isDone() && page2.isDone() && page3.isDone())) {
Thread.sleep(10); //10-millisecond pause between each check
}
// Print results, including elapsed time
logger.info("Elapsed time: " + (System.currentTimeMillis() - start));
logger.info("--> " + page1.get());
logger.info("--> " + page2.get());
logger.info("--> " + page3.get());
}
}
自定義異步任務異常
當方法返回類型為Future時,異常處理很容易– Future.get()方法將引發異常。但是,如果返回類型為void,則異常不會傳播到調用線程。因此,我們需要添加額外的配置來處理異常。我們將通過實現AsyncUncaughtExceptionHandler接口來創建自定義異步異常處理程序。
package com.example.springboot.async.exception;
import org.springframework.aop.interceptor.AsyncUncaughtExceptionHandler;
import java.lang.reflect.Method;
/**
* <pre>
* Copy @ https://www.baeldung.com/spring-async
* </pre>
*
* <pre>
* 修改記錄
* 修改后版本: 修改人: 修改日期: 2020/07/20 11:08 修改內容:
* </pre>
*/
public class CustomAsyncExceptionHandler implements AsyncUncaughtExceptionHandler {
@Override
public void handleUncaughtException(
Throwable throwable, Method method, Object... obj) {
System.out.println("Exception message - " + throwable.getMessage());
System.out.println("Method name - " + method.getName());
for (Object param : obj) {
System.out.println("Parameter value - " + param);
}
}
}
需要重寫getAsyncUncaughtExceptionHandler()方法以返回我們的自定義異步異常處理程序
@Configuration
@EnableAsync
public class AsyncConfiguration extends AsyncConfigurerSupport {
// ...
@Override
public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
return new CustomAsyncExceptionHandler();
}
}
啟動之后,可以看到如下信息,因為是多線程方式,所以都不是在main線程里的,異步執行的
如果注釋@Async注解,再次啟動,會發現都在main主線程里執行程序
代碼例子下載:code download