spring 多线程异步调用 - 提高程序执行效率
为什么要用异步?
当需要调用多个服务时,使用传统的同步调用来执行时,是这样的
- 调用服务A
- 等待服务A的响应
- 调用服务B
- 等待服务B的响应
- 调用服务C
- 等待服务C的响应
- 根据从服务A、服务B和服务C返回的数据完成业务逻辑,然后结束
如果每个服务需要3秒的响应时间,这样顺序执行下来,可能需要9秒以上才能完成业务逻辑,但是如果我们使用异步调用
- 调用服务A
- 调用服务B
- 调用服务C
- 然后等待从服务A、B和C的响应
- 根据从服务A、服务B和服务C返回的数据完成业务逻辑,然后结束
理论上 3秒左右即可完成同样的业务逻辑
Talk is cheap. Show me the code
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 + "]";
}
}
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<User> 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 3s for demonstration purposes
Thread.sleep(3000L);
return CompletableFuture.completedFuture(results);
}
}
The
findUser
method is flagged with Spring’s@Async
annotation, indicating it will run on a separate thread. The method’s return type isCompletableFuture<User>
instead ofUser
, a requirement for any asynchronous service.
findUser
方法被标记为Spring的@Async
注解,表示它将在一个单独的线程上运行。该方法的返回类型是CompleetableFuture<user>
而不是User
,这是任何异步服务的要求。
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 App {
public static void main(String[] args) {
// close the application context to shut down the custom ExecutorService
SpringApplication.run(App.class, args).close();
}
@Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("GithubLookup-");
executor.initialize();
return executor;
}
}
The
@EnableAsync
annotation switches on Spring’s ability to run@Async
methods in a background thread pool. This class also customizes the usedExecutor
. In our case, we want to limit the number of concurrent threads to 2 and limit the size of the queue to 500. There are many more things you can tune. By default, aSimpleAsyncTaskExecutor
is used.
@EnableAsync
注解开启Spring在后台线程池中运行@Async
方法的能力。该类也可以自定义使用的Executor
。在我们的示例中,我们希望将并发线程的数量限制为2,并将队列的大小限制为500。有很多你可以配置的东西。默认情况下,使用SimpleAsyncTaskExecutor。
import java.util.concurrent.CompletableFuture;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;
import com.gitee.taven.entity.User;
import com.gitee.taven.service.GitHubLookupService;
@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<User> page1 = gitHubLookupService.findUser("PivotalSoftware");
CompletableFuture<User> page2 = gitHubLookupService.findUser("CloudFoundry");
CompletableFuture<User> page3 = gitHubLookupService.findUser("Spring-Projects");
// Wait until they are all done
CompletableFuture.allOf(page1,page2,page3).join();
// Print results, including elapsed time
float exc = (float)(System.currentTimeMillis() - start)/1000;
logger.info("Elapsed time: " + exc + " seconds");
logger.info("--> " + page1.get());
logger.info("--> " + page2.get());
logger.info("--> " + page3.get());
}
}
通过实现 CommandLineRunner
调用 service 服务,我们设置了 Thread.sleep(3000L);
运行demo,4.73s 结束战斗!