Spring @Async 注解允许我们在Spring中创建异步方法。让我们在这个Spring框架的教程中探讨 @Async
。简而言之,当我们给一个bean的方法注解了@Async
注解时,Spring会在一个单独的线程中执行它,并且方法的调用者不会等待方法完成执行。在这个示例中,我们将定义自己的服务并使用Spring Boot 2。让我们开始吧!
Spring @Async 示例
我们将使用Maven创建一个演示项目。要创建项目,请在您将用作工作空间的目录中执行以下命令:
mvn archetype:generate -DgroupId=com.journaldev.asynchmethods -DartifactId=JD-SpringBoot-AsyncMethods -DarchetypeArtifactId=maven-archetype-quickstart -DinteractiveMode=false
如果您是第一次运行Maven,执行生成命令可能需要几秒钟,因为Maven必须下载所有所需的插件和构件,以完成生成任务。以下是项目创建的样子:创建项目后,可以随时在您喜欢的集成开发环境(IDE)中打开它。下一步是向项目添加适当的Maven依赖项。以下是包含适当依赖项的
pom.xml
文件:
<parent>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-parent</artifactId>
<version>2.0.1.RELEASE</version>
<relativePath/> <!-- lookup parent from repository -->
</parent>
<dependencies>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-web</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-test</artifactId>
<scope>test</scope>
</dependency>
</dependencies>
<build>
<plugins>
<plugin>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-maven-plugin</artifactId>
</plugin>
</plugins>
</build>
最后,为了了解添加此依赖项时添加到项目中的所有JAR文件,我们可以运行一个简单的Maven命令,允许我们查看项目的完整依赖关系树。以下是我们可以使用的命令:
mvn dependency:tree
启用异步支持
启用异步支持也只是一个简单的注解问题。除了启用异步执行之外,我们还将利用Executor来定义线程限制。更多内容等我们编写代码时再说:
package com.journaldev.asynchexample;
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 AsyncApp {
...
}
在这里,我们使用了@EnableAsync
注解,该注解启用了Spring在后台线程池中运行异步方法的能力。接下来,我们还添加了上述的Executor:
@Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("JDAsync-");
executor.initialize();
return executor;
}
在这里,我们设置最多同时运行2个线程,队列大小设置为500。以下是带有导入语句的类的完整代码:
package com.journaldev.asynchexample;
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 AsyncApp {
public static void main(String[] args) {
SpringApplication.run(AsyncApp.class, args).close();
}
@Bean
public Executor asyncExecutor() {
ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();
executor.setCorePoolSize(2);
executor.setMaxPoolSize(2);
executor.setQueueCapacity(500);
executor.setThreadNamePrefix("JDAsync-");
executor.initialize();
return executor;
}
}
接下来我们将创建一个服务,实际上是利用线程执行。
创建一个模型
我们将使用一个公共电影API,它只返回电影的数据。我们将为此定义我们的模型:
package com.journaldev.asynchexample;
import com.fasterxml.jackson.annotation.JsonIgnoreProperties;
@JsonIgnoreProperties(ignoreUnknown = true)
public class MovieModel {
private String title;
private String producer;
// 标准的getter和setter
@Override
public String toString() {
return String.format("MovieModel{title='%s', producer='%s'}", title, producer);
}
}
我们使用了@JsonIgnoreProperties
,这样如果响应中有更多的属性,它们可以被Spring安全地忽略。
创建服务
是时候定义我们的服务了,这个服务将调用提及的电影API。我们将使用简单的RestTemplate来访问GET API并异步获取结果。让我们来看一下我们使用的示例代码:
package com.journaldev.asynchexample;
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 MovieService {
private static final Logger LOG = LoggerFactory.getLogger(MovieService.class);
private final RestTemplate restTemplate;
public MovieService(RestTemplateBuilder restTemplateBuilder) {
this.restTemplate = restTemplateBuilder.build();
}
@Async
public CompletableFuture lookForMovie(String movieId) throws InterruptedException {
LOG.info("Looking up Movie ID: {}", movieId);
String url = String.format("https://ghibliapi.herokuapp.com/films/%s", movieId);
MovieModel results = restTemplate.getForObject(url, MovieModel.class);
// 为演示目的人工延迟1秒
Thread.sleep(1000L);
return CompletableFuture.completedFuture(results);
}
}
这个类是一个@Service
,使其符合Spring组件扫描的条件。lookForMovie
方法的返回类型是CompletableFuture
,这是任何异步服务的要求。由于API的时间可能有所不同,我们添加了一个2秒的延迟以进行演示。
创建一个命令行运行器
我们将使用CommandLineRunner来运行我们的应用程序,这是测试我们应用程序的最简单方法。CommandLineRunner会在应用程序的所有bean初始化之后立即运行。让我们看看CommandLineRunner的代码:
package com.journaldev.asynchexample;
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 ApplicationRunner implements CommandLineRunner {
private static final Logger LOG = LoggerFactory.getLogger(ApplicationRunner.class);
private final MovieService movieService;
public ApplicationRunner(MovieService movieService) {
this.movieService = movieService;
}
@Override
public void run(String... args) throws Exception {
// 启动时钟
long start = System.currentTimeMillis();
// 启动多个异步查找
CompletableFuture page1 = movieService.lookForMovie("58611129-2dbc-4a81-a72f-77ddfc1b1b49");
CompletableFuture page2 = movieService.lookForMovie("2baf70d1-42bb-4437-b551-e5fed5a87abe");
CompletableFuture page3 = movieService.lookForMovie("4e236f34-b981-41c3-8c65-f8c9000b94e7");
// 加入所有线程,以便我们等待所有线程完成
CompletableFuture.allOf(page1, page2, page3).join();
// 打印结果,包括经过的时间
LOG.info("Elapsed time: " + (System.currentTimeMillis() - start));
LOG.info("--> " + page1.get());
LOG.info("--> " + page2.get());
LOG.info("--> " + page3.get());
}
}
我们只是使用RestTemplate来访问我们用一些随机选择的电影ID测试的示例API。我们将运行我们的应用程序,看看它显示什么输出。
运行应用程序
当我们运行应用程序时,我们将看到以下输出:
2018-04-13 INFO 17868 --- [JDAsync-1] c.j.a.MovieService : Looking up Movie ID: 58611129-2dbc-4a81-a72f-77ddfc1b1b49
2018-04-13 08:00:09.518 INFO 17868 --- [JDAsync-2] c.j.a.MovieService : Looking up Movie ID: 2baf70d1-42bb-4437-b551-e5fed5a87abe
2018-04-13 08:00:12.254 INFO 17868 --- [JDAsync-1] c.j.a.MovieService : Looking up Movie ID: 4e236f34-b981-41c3-8c65-f8c9000b94e7
2018-04-13 08:00:13.565 INFO 17868 --- [main] c.j.a.ApplicationRunner : Elapsed time: 4056
2018-04-13 08:00:13.565 INFO 17868 --- [main] c.j.a.ApplicationRunner : --> MovieModel{title='My Neighbor Totoro', producer='Hayao Miyazaki'}
2018-04-13 08:00:13.565 INFO 17868 --- [main] c.j.a.ApplicationRunner : --> MovieModel{title='Castle in the Sky', producer='Isao Takahata'}
2018-04-13 08:00:13.566 INFO 17868 --- [main] c.j.a.ApplicationRunner : --> MovieModel{title='Only Yesterday', producer='Toshio Suzuki'}
如果您仔细观察,将只有两个线程被设置为在应用程序中执行,分别是JDAsync-1
和JDAsync-2
。
结论
在本课程中,我们学习了如何在Spring Boot 2中使用Spring的异步功能。阅读更多与Spring相关的文章,请点击这里。
下载源代码
Source:
https://www.digitalocean.com/community/tutorials/spring-async-annotation