dedecms 网站首页标签,凡科建站怎么样,百度刷seo关键词排名,专业建设外贸网站制作江门以前#xff0c;我们开始使用spring和TaskExecutor #xff0c;因此我们对如何在spring应用程序中使用线程更加熟悉。 但是#xff0c;使用任务执行程序可能比较麻烦#xff0c;尤其是当我们需要执行简单的操作时。 Spring的异步方法可以解决。 您不必为可运行对象和Tas… 以前我们开始使用spring和TaskExecutor 因此我们对如何在spring应用程序中使用线程更加熟悉。 但是使用任务执行程序可能比较麻烦尤其是当我们需要执行简单的操作时。 Spring的异步方法可以解决。 您不必为可运行对象和TaskExecutor烦恼而是为了简化异步功能而对执行程序的控制权进行了交易。 为了在另一个线程中执行函数您要做的就是使用Async注释对函数进行注释。 异步方法有两种模式。 一劳永逸模式一种返回void类型的方法。 AsyncTransactionalpublic void printEmployees() {ListEmployee employees entityManager.createQuery(SELECT e FROM Employee e).getResultList();employees.stream().forEach(e-System.out.println(e.getEmail()));} 结果检索模式一种返回未来类型的方法。 AsyncTransactionalpublic CompletableFutureListEmployee fetchEmployess() {ListEmployee 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