欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

Spring中@Async注解執(zhí)行異步任務的方法

 更新時間:2018年06月06日 09:42:39   作者:liaosilzu2007  
在業(yè)務處理中,有些業(yè)務使用異步的方式更為合理,這篇文章主要介紹了Spring中@Async注解執(zhí)行異步任務的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

引言

在業(yè)務處理中,有些業(yè)務使用異步的方式更為合理。比如在某個業(yè)務邏輯中,把一些數(shù)據(jù)存入到redis緩存中,緩存只是一個輔助的功能,成功或者失敗對主業(yè)務并不會產(chǎn)生根本影響,這個過程可以通過異步的方法去進行。

Spring中通過在方法上設置@Async注解,可使得方法被異步調(diào)用。也就是說該方法會在調(diào)用時立即返回,而這個方法的實際執(zhí)行交給Spring的TaskExecutor去完成。

代碼示例

項目是一個普通的Spring的項目,Spring的配置文件:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://www.springframework.org/schema/beans"
  xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
  xmlns:context="http://www.springframework.org/schema/context"
  xmlns:task="http://www.springframework.org/schema/task"
  xsi:schemaLocation="http://www.springframework.org/schema/beans
  http://www.springframework.org/schema/beans/spring-beans-4.0.xsd
  http://www.springframework.org/schema/context
  http://www.springframework.org/schema/context/spring-context.xsd
  http://www.springframework.org/schema/task
  http://www.springframework.org/schema/task/spring-task.xsd">

 <!-- 包掃描 -->
 <context:component-scan base-package="com.lzumetal.ssm"/>

 <!-- 執(zhí)行異步任務的線程池TaskExecutor -->
 <task:executor id="myexecutor" pool-size="5" />
 <task:annotation-driven executor="myexecutor"/>

</beans>

兩個Service類:

package com.lzumetal.ssm.anotation.service;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.concurrent.ExecutionException;
import java.util.concurrent.Future;

/**
 * 業(yè)務Service
 */
@Service
public class BusinessService {

 private static final Logger log = LoggerFactory.getLogger(BusinessService.class);

 @Autowired
 private CacheService cacheService;


 public void doBusiness() {
  log.error("start to deal with our business");
  cacheService.cacheData();
  log.error("comlete service operation");
 }

 /**
  * 獲取異步方法執(zhí)行的返回值
  */
 public void doBusinessWithAsyncReturn() throws ExecutionException, InterruptedException {
  log.error("start to deal with our business");
  Future<String> future = cacheService.cacheDataWithReturn();
  log.error(future.get()); //future.get()方法是會阻塞的
  log.error("comlete service operation");
 }
}
package com.lzumetal.ssm.anotation.service;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.AsyncResult;
import org.springframework.stereotype.Service;

import java.util.concurrent.Future;
import java.util.concurrent.TimeUnit;

/**
 * 緩存服務
 */
@Service
public class CacheService {

 private static final Logger log = LoggerFactory.getLogger(CacheService.class);


 @Async(value = "myexecutor") //指定執(zhí)行任務的TaskExecutor
 public void cacheData() {
  try {
   TimeUnit.SECONDS.sleep(3L);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  log.error("success store the result to cache");
 }


 @Async
 public Future<String> cacheDataWithReturn() {
  try {
   TimeUnit.SECONDS.sleep(3L);
  } catch (InterruptedException e) {
   e.printStackTrace();
  }
  log.error("success store the result to cache");
  //返回的結(jié)果需要通過AsyncResult這個類包裝
  return new AsyncResult<>("Async operation success");
 }
}

測試類:

package com.lzumetal.ssm.anotation.test;

import com.lzumetal.ssm.anotation.service.BusinessService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.test.context.ContextConfiguration;
import org.springframework.test.context.junit4.SpringJUnit4ClassRunner;

import java.util.concurrent.TimeUnit;

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(locations = {"classpath:spring-context.xml"})
public class MainTest {


 @Autowired
 private BusinessService businessService;


 @Test
 public void test() throws InterruptedException {
  businessService.doBusiness();
  //不讓主線程過早結(jié)束,否則控制臺看不到異步方法中的輸出內(nèi)容
  TimeUnit.SECONDS.sleep(5L);  
 }

 @Test
 public void testAsyncReturn() throws Exception {
  businessService.doBusinessWithAsyncReturn();
  TimeUnit.SECONDS.sleep(5L);
 }

}

執(zhí)行test()方法的結(jié)果:

22:20:33,207  INFO main support.DefaultTestContextBootstrapper:260 - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
22:20:33,226  INFO main support.DefaultTestContextBootstrapper:209 - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
22:20:33,227  INFO main support.DefaultTestContextBootstrapper:187 - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@100fc185, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@643b1d11, org.springframework.test.context.support.DirtiesContextTestExecutionListener@2ef5e5e3, org.springframework.test.context.transaction.TransactionalTestExecutionListener@36d4b5c, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@6d00a15d]22:20:33,324  INFO main xml.XmlBeanDefinitionReader:317 - Loading XML bean definitions from class path resource [spring-context.xml]
22:20:33,585  INFO main support.GenericApplicationContext:583 - Refreshing org.springframework.context.support.GenericApplicationContext@4f7d0008: startup date [Wed May 30 22:20:33 CST 2018]; root of context hierarchy
22:20:33,763  INFO main concurrent.ThreadPoolTaskExecutor:165 - Initializing ExecutorService
22:20:33,766  INFO main support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker:325 - Bean 'myexecutor' of type [org.springframework.scheduling.config.TaskExecutorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
22:20:33,767  INFO main support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker:325 - Bean 'myexecutor' of type [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
22:20:34,107 ERROR main service.BusinessService:24 - start to deal with our business
22:20:34,113 ERROR main service.BusinessService:26 - comlete service operation
22:20:37,166 ERROR myexecutor-1 service.CacheService:28 - success store the result to cache
22:20:39,117  INFO Thread-0 support.GenericApplicationContext:984 - Closing org.springframework.context.support.GenericApplicationContext@4f7d0008: startup date [Wed May 30 22:20:33 CST 2018]; root of context hierarchy
22:20:39,118  INFO Thread-0 concurrent.ThreadPoolTaskExecutor:203 - Shutting down ExecutorService

執(zhí)行testAsyncReturn()方法的結(jié)果:

21:38:16,908  INFO main support.DefaultTestContextBootstrapper:260 - Loaded default TestExecutionListener class names from location [META-INF/spring.factories]: [org.springframework.test.context.web.ServletTestExecutionListener, org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener, org.springframework.test.context.support.DependencyInjectionTestExecutionListener, org.springframework.test.context.support.DirtiesContextTestExecutionListener, org.springframework.test.context.transaction.TransactionalTestExecutionListener, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener]
21:38:16,926  INFO main support.DefaultTestContextBootstrapper:209 - Could not instantiate TestExecutionListener [org.springframework.test.context.web.ServletTestExecutionListener]. Specify custom listener classes or make the default listener classes (and their required dependencies) available. Offending class: [javax/servlet/ServletContext]
21:38:16,927  INFO main support.DefaultTestContextBootstrapper:187 - Using TestExecutionListeners: [org.springframework.test.context.support.DirtiesContextBeforeModesTestExecutionListener@100fc185, org.springframework.test.context.support.DependencyInjectionTestExecutionListener@643b1d11, org.springframework.test.context.support.DirtiesContextTestExecutionListener@2ef5e5e3, org.springframework.test.context.transaction.TransactionalTestExecutionListener@36d4b5c, org.springframework.test.context.jdbc.SqlScriptsTestExecutionListener@6d00a15d]21:38:17,025  INFO main xml.XmlBeanDefinitionReader:317 - Loading XML bean definitions from class path resource [spring-context.xml]
21:38:17,263  INFO main support.GenericApplicationContext:583 - Refreshing org.springframework.context.support.GenericApplicationContext@4f7d0008: startup date [Wed May 30 21:38:17 CST 2018]; root of context hierarchy
21:38:17,405  INFO main concurrent.ThreadPoolTaskExecutor:165 - Initializing ExecutorService
21:38:17,407  INFO main support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker:325 - Bean 'myexecutor' of type [org.springframework.scheduling.config.TaskExecutorFactoryBean] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
21:38:17,407  INFO main support.PostProcessorRegistrationDelegate$BeanPostProcessorChecker:325 - Bean 'myexecutor' of type [org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor] is not eligible for getting processed by all BeanPostProcessors (for example: not eligible for auto-proxying)
21:38:17,692 ERROR main service.BusinessService:35 - start to deal with our business
21:38:20,833 ERROR myexecutor-1 service.CacheService:39 - success store the result to cache
21:38:20,834 ERROR main service.BusinessService:37 - Async operation success
21:38:20,835 ERROR main service.BusinessService:38 - comlete service operation
21:38:25,838  INFO Thread-0 support.GenericApplicationContext:984 - Closing org.springframework.context.support.GenericApplicationContext@4f7d0008: startup date [Wed May 30 21:38:17 CST 2018]; root of context hierarchy
21:38:25,839  INFO Thread-0 concurrent.ThreadPoolTaskExecutor:203 - Shutting down ExecutorService

@Async的使用注意點

  1. 返回值:不要返回值直接void;需要返回值用AsyncResult或者CompletableFuture
  2. 可自定義執(zhí)行器并指定例如:@Async("otherExecutor")
  3. @Async必須不同類間調(diào)用: A類—>B類.C方法()(@Async注釋在B類/方法中),如果在同一個類中調(diào)用,會變同步執(zhí)行,例如:A類.B()—>A類.@Async C()。
  4. @Async也可以加到類,表示這個類的所有方法都是異步執(zhí)行,并且方法上的注解會覆蓋類上的注解。但一般不這么用!

以上就是本文的全部內(nèi)容,希望對大家的學習有所幫助,也希望大家多多支持腳本之家。

相關(guān)文章

  • Java多線程之如何確定線程數(shù)的方法

    Java多線程之如何確定線程數(shù)的方法

    創(chuàng)建線程和銷毀線程都是比較耗時的操作,如果每個任務都創(chuàng)建一個線程去處理,這樣線程會越來越多,那么應該如何確定線程的數(shù)量,本文就詳細的介紹一下,感興趣的可以了解一下
    2022-03-03
  • java高級用法之JNA中的回調(diào)問題

    java高級用法之JNA中的回調(diào)問題

    這篇文章主要介紹了java高級用法之:JNA中的回調(diào),為了方便和native方法進行交互,JNA中同樣提供了Callback用來進行回調(diào),JNA中回調(diào)的本質(zhì)是一個指向native函數(shù)的指針,通過這個指針可以調(diào)用native函數(shù)中的方法,一起來看看吧
    2022-05-05
  • 解決idea導入ssm項目啟動tomcat報錯404的問題

    解決idea導入ssm項目啟動tomcat報錯404的問題

    今天小編就為大家分享一篇解決idea導入ssm項目啟動tomcat報錯404的問題,具有很好的參考價值,希望對大家有所幫助。一起跟隨小編過來看看吧
    2018-08-08
  • Java求素數(shù)和最大公約數(shù)的簡單代碼示例

    Java求素數(shù)和最大公約數(shù)的簡單代碼示例

    這篇文章主要介紹了Java求素數(shù)和最大公約數(shù)的簡單代碼示例,其中作者創(chuàng)建的Fraction類可以用來進行各種分數(shù)運算,需要的朋友可以參考下
    2015-09-09
  • java向文件末尾添加內(nèi)容示例分享

    java向文件末尾添加內(nèi)容示例分享

    本文為大家提供一個java向文件末尾添加內(nèi)容的示例分享,大家參考使用吧
    2014-01-01
  • Java實現(xiàn)簡單銀行ATM功能

    Java實現(xiàn)簡單銀行ATM功能

    這篇文章主要為大家詳細介紹了Java實現(xiàn)銀行ATM簡單功能,文中示例代碼介紹的非常詳細,具有一定的參考價值,感興趣的小伙伴們可以參考一下
    2020-10-10
  • 詳解PowerDesigner之CDM、PDM、SQL之間轉(zhuǎn)換

    詳解PowerDesigner之CDM、PDM、SQL之間轉(zhuǎn)換

    這篇文章主要介紹了詳解PowerDesigner之CDM、PDM、SQL之間轉(zhuǎn)換的相關(guān)資料,希望通過本文能幫助到大家,需要的朋友可以參考下
    2017-10-10
  • Mybatis自定義typeHandle過程解析

    Mybatis自定義typeHandle過程解析

    這篇文章主要介紹了Mybatis自定義typeHandle過程解析,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友可以參考下
    2020-04-04
  • SWT(JFace)體驗之FormLayout布局

    SWT(JFace)體驗之FormLayout布局

    SWT(JFace)體驗之FormLayout布局示例代碼。
    2009-06-06
  • 深入理解JVM之Class類文件結(jié)構(gòu)詳解

    深入理解JVM之Class類文件結(jié)構(gòu)詳解

    這篇文章主要介紹了深入理解JVM之Class類文件結(jié)構(gòu),結(jié)合實例形式詳細分析了Class類文件結(jié)構(gòu)相關(guān)概念、原理、結(jié)構(gòu)、常用方法與屬性,需要的朋友可以參考下
    2019-09-09

最新評論