- @Async 注解实现异步调用
- 使用方法
- 注意事项
- 示例
- 创建用户表现层
- 创建查找服务
- 应用程序
- 在 SpringBootApplication 中添加 @EnableAsync
- 使用Bean 方法配置线程池(注意, 用于生产必须配置线程池)
- 实现 @Service 类是的spring 上下文能够检测到异步调用服务
- 在方法中添加 @Async 注解
- 详细请参照示例和注意事项
- @Async 方法必须在所属的@Service 之外被调用, 不能自己调用@Async方法
- 在SpringBootApplication 配置线程池, 推荐使用ThreadPoolTaskExecutor.
- 线程池必须限制队列大小, 否则将导致OOM.
- setCorePoolSize 和 setMaxPoolSize 建议保持一致
- @Async 方法一定要注意实现线程安全, 后面会有文章单独介绍线程池中的线程安全下如何保持高性能
package com.example.asyncmethod;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown=true)
public class User {
private String name;
private String blog;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getBlog() {
return blog;
}
public void setBlog(String blog) {
this.blog = blog;
}
@Override
public String toString() {
return "User [name=" + name + ", blog=" + blog + "]";
}
}
创建查找服务
package com.example.asyncmethod;
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;
@Service
public class GitHubLookupService {
private static final Logger logger = LoggerFactory.getLogger(GitHubLookupService.class);
private final RestTemplate restTemplate;
public GitHubLookupService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
@Async
public CompletableFuture findUser(String user) throws InterruptedException {
logger.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);
}
}
GitHubLookupService 类使用 Spring 的 RestTemplate 调用远程 REST (api.github.com/users/),然后转换为用户对象。
类中必须要标有 @Service (或者@Component) 注释,使其成为 Spring 扫描组件的时候,被检测并添加到程序上下文中。
这里是关键, findUser 方法使用 Spring 的 @Async 注解,本例中使用线程池中运行该方法。
方法的返回值要么是void, 要么是Futrue 类, 本例返回类型是 CompletableFuture。
package com.example.asyncmethod;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@SpringBootApplication
@EnableAsync
public class AsyncMethodApplication {
public static void main(String[] args) {
// close the application context to shut down the custom ExecutorService
SpringApplication.run(AsyncMethodApplication.class, args).close();
}
@Bean
public Executor taskExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2); //初始并发线程的数量限制
executor.setMaxPoolSize(2); //最大并发线程的数量限制, 强烈建议初始值和最大值保持一致
executor.setQueueCapacity(500); //队列大小
executor.setThreadNamePrefix("example-");
executor.initialize();
return executor;
}
}
必须通过@EnableAsync 注解开启 Spring 在后台线程池中运行 @Async 方法功能。 通过生成bean 来定制 Executor, 本例中为taskExecutor。
- 异步调用者必须在 @Service 异步调用类之外, 才能生效.
package com.example.asyncmethod;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import java.util.concurrent.CompletableFuture;
@Component
public class AppRunner implements CommandLineRunner {
private static final Logger logger = LoggerFactory.getLogger(AppRunner.class);
private final GitHubLookupService gitHubLookupService;
public AppRunner(GitHubLookupService gitHubLookupService) {
this.gitHubLookupService = gitHubLookupService;
}
@Override
public void run(String... args) throws Exception {
// Start the clock
long start = System.currentTimeMillis();
// Kick of multiple, asynchronous lookups
CompletableFuture page1 = gitHubLookupService.findUser("PivotalSoftware");
CompletableFuture page2 = gitHubLookupService.findUser("CloudFoundry");
CompletableFuture page3 = gitHubLookupService.findUser("Spring-Projects");
// Wait until they are all done
CompletableFuture.allOf(page1,page2,page3).join();
// Print results, including elapsed time
logger.info("Elapsed time: " + (System.currentTimeMillis() - start));
logger.info("--> " + page1.get());
logger.info("--> " + page2.get());
logger.info("--> " + page3.get());
}
}



