弹簧和线程:异步
以前,我們開始使用spring和TaskExecutor ,因此我們對(duì)如何在spring應(yīng)用程序中使用線程更加熟悉。
但是,使用任務(wù)執(zhí)行程序可能比較麻煩,尤其是當(dāng)我們需要執(zhí)行簡(jiǎn)單的操作時(shí)。
Spring的異步方法可以解決。
您不必為可運(yùn)行對(duì)象和TaskExecutor煩惱,而是為了簡(jiǎn)化異步功能而對(duì)執(zhí)行程序的控制權(quán)進(jìn)行了交易。
為了在另一個(gè)線程中執(zhí)行函數(shù),您要做的就是使用@Async注釋對(duì)函數(shù)進(jìn)行注釋。
異步方法有兩種模式。
一勞永逸模式:一種返回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()));}結(jié)果檢索模式:一種返回未來類型的方法。
@Async@Transactionalpublic CompletableFuture<List<Employee>> fetchEmployess() {List<Employee> employees = entityManager.createQuery("SELECT e FROM Employee e").getResultList();return CompletableFuture.completedFuture(employees);}要特別注意以下事實(shí):@Async注釋如果被'this'調(diào)用,則不會(huì)起作用。 @Async的行為就像@Transactional批注一樣。 因此,您需要將異步功能公開。 您可以在aop代理文檔中找到更多信息。
但是,僅使用@Async注釋是不夠的。 我們需要通過在我們的配置類之一中使用@EnableAsync注釋來啟用Spring的異步方法執(zhí)行功能。
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;}}下一個(gè)問題是我們?nèi)绾温暶鳟惒胶瘮?shù)將使用的資源和線程池。 我們可以從文檔中得到答案。
默認(rèn)情況下,Spring將搜索關(guān)聯(lián)的線程池定義:上下文中的唯一TaskExecutor bean,否則為名為“ taskExecutor”的Executor bean。 如果二者都不可解決,則將使用SimpleAsyncTaskExecutor處理異步方法調(diào)用。
但是,在某些情況下,我們不希望同一線程池運(yùn)行應(yīng)用程序的所有任務(wù)。 我們可能需要具有不同配置的單獨(dú)線程池來支持我們的功能。
為此,我們將可能要用于每個(gè)函數(shù)的執(zhí)行程序的名稱傳遞給@Async批注。
例如,配置了名稱為“ specificTaskExecutor”的執(zhí)行程序。
@Configuration @EnableAsync public class ThreadConfig {@Bean(name = "specificTaskExecutor")public TaskExecutor specificTaskExecutor() {ThreadPoolTaskExecutor executor = new ThreadPoolTaskExecutor();executor.initialize();return executor;}}然后,我們的函數(shù)應(yīng)設(shè)置限定符值,以確定特定執(zhí)行程序或TaskExecutor的目標(biāo)執(zhí)行程序。
@Async("specificTaskExecutor") public void runFromAnotherThreadPool() {System.out.println("You function code here"); }下一篇文章我們將討論線程事務(wù)。
您可以在github上找到源代碼。
翻譯自: https://www.javacodegeeks.com/2017/10/spring-threads-async.html
總結(jié)
- 上一篇: (安卓 ios互通游戏)
- 下一篇: 印章备案号查询平台(印章备案号)