以前,我们开始使用spring和TaskExecutor ,因此我们对如何在spring应用程序中使用线程更加熟悉。
但是,使用任务执行程序可能比较麻烦,尤其是当我们需要执行简单的操作时。
Spring的异步方法可以解决。
您不必为可运行对象和TaskExecutor烦恼,而是为了简化异步功能而对执行程序的控制权进行了交易。
为了在另一个线程中执行函数,您要做的就是使用@Async注释对函数进行注释。
异步方法有两种模式。
一劳永逸模式:一种返回void类型的方法。
@Async@Transactionalpublic void printEmployees() {List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e").getResultList();employees.stream().forEach(e->System.out.println(e.getEmail()));}
结果检索模式:一种返回未来类型的方法。
@Async@Transactionalpublic CompletableFuture<List<Employee>> fetchEmployess() {List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e").getResultList();return CompletableFuture.completedFuture(employees);}
要特别注意以下事实:@Async注释如果被'this'调用,则不会起作用。 @Async的行为就像@Transactional批注一样。 因此,您需要将异步功能公开。 您可以在aop代理文档中找到更多信息。
但是,仅使用@Async注释是不够的。 我们需要通过在我们的配置类之一中使用@EnableAsync注释来启用Spring的异步方法执行功能。
package com.gkatzioura.config;import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.core.task.TaskExecutor;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;import java.util.concurrent.Executor;/*** Created by gkatzioura on 4/26/17.*/
@Configuration
@EnableAsync
public class ThreadConfig {@Beanpublic TaskExecutor threadPoolTaskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.setCorePoolSize(4);executor.setMaxPoolSize(4);executor.setThreadNamePrefix("sgfgd");executor.initialize();return executor;}}
下一个问题是我们如何声明异步函数将使用的资源和线程池。 我们可以从文档中得到答案。
默认情况下,Spring将搜索关联的线程池定义:上下文中的唯一TaskExecutor bean,否则为名为“ taskExecutor”的Executor bean。 如果二者都不可解决,则将使用SimpleAsyncTaskExecutor处理异步方法调用。
但是,在某些情况下,我们不希望同一线程池运行应用程序的所有任务。 我们可能需要具有不同配置的单独线程池来支持我们的功能。
为此,我们将可能要用于每个函数的执行程序的名称传递给@Async批注。
例如,配置了名称为“ specificTaskExecutor”的执行程序。
@Configuration
@EnableAsync
public class ThreadConfig {@Bean(name = "specificTaskExecutor")public TaskExecutor specificTaskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.initialize();return executor;}}
然后,我们的函数应设置限定符值,以确定特定执行程序或TaskExecutor的目标执行程序。
@Async("specificTaskExecutor")
public void runFromAnotherThreadPool() {System.out.println("You function code here");
}
下一篇文章我们将讨论线程事务。
您可以在github上找到源代码。
翻译自: https://www.javacodegeeks.com/2017/10/spring-threads-async.html