国产片侵犯亲女视频播放_亚洲精品二区_在线免费国产视频_欧美精品一区二区三区在线_少妇久久久_在线观看av不卡

服務(wù)器之家:專注于服務(wù)器技術(shù)及軟件下載分享
分類導(dǎo)航

PHP教程|ASP.NET教程|Java教程|ASP教程|編程技術(shù)|正則表達(dá)式|C/C++|IOS|C#|Swift|Android|VB|R語言|JavaScript|易語言|vb.net|

服務(wù)器之家 - 編程語言 - Java教程 - Spring中@Async注解執(zhí)行異步任務(wù)的方法

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

2021-05-07 13:14liaosilzu2007 Java教程

在業(yè)務(wù)處理中,有些業(yè)務(wù)使用異步的方式更為合理,這篇文章主要介紹了Spring中@Async注解執(zhí)行異步任務(wù)的方法,小編覺得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過來看看吧

引言

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

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

代碼示例

項(xiàng)目是一個(gè)普通的Spring的項(xiàng)目,Spring的配置文件:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?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í)行異步任務(wù)的線程池TaskExecutor -->
 <task:executor id="myexecutor" pool-size="5" />
 <task:annotation-driven executor="myexecutor"/>
 
</beans>

兩個(gè)Service類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
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è)務(wù)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()方法是會(huì)阻塞的
  log.error("comlete service operation");
 }
}
?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
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;
 
/**
 * 緩存服務(wù)
 */
@Service
public class CacheService {
 
 private static final Logger log = LoggerFactory.getLogger(CacheService.class);
 
 
 @Async(value = "myexecutor") //指定執(zhí)行任務(wù)的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這個(gè)類包裝
  return new AsyncResult<>("Async operation success");
 }
}

測試類:

?
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
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é)束,否則控制臺(tái)看不到異步方法中的輸出內(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的使用注意點(diǎn)

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

以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持服務(wù)器之家。

原文鏈接:https://segmentfault.com/a/1190000015190901

延伸 · 閱讀

精彩推薦
Weibo Article 1 Weibo Article 2 Weibo Article 3 Weibo Article 4 Weibo Article 5 Weibo Article 6 Weibo Article 7 Weibo Article 8 Weibo Article 9 Weibo Article 10 Weibo Article 11 Weibo Article 12 Weibo Article 13 Weibo Article 14 Weibo Article 15 Weibo Article 16 Weibo Article 17 Weibo Article 18 Weibo Article 19 Weibo Article 20 Weibo Article 21 Weibo Article 22 Weibo Article 23 Weibo Article 24 Weibo Article 25 Weibo Article 26 Weibo Article 27 Weibo Article 28 Weibo Article 29 Weibo Article 30 Weibo Article 31 Weibo Article 32 Weibo Article 33 Weibo Article 34 Weibo Article 35 Weibo Article 36 Weibo Article 37 Weibo Article 38 Weibo Article 39 Weibo Article 40
主站蜘蛛池模板: 国产成人一区二区三区 | 国产98色在线 | 日韩 | 国产高潮呻吟av | 亚洲欧美一区二区三区国产精品 | 九九热精品视频在线观看 | 久久小草 | 成人久久久精品国产乱码一区二区 | 一级二级在线观看 | 激情婷婷丁香 | 91亚洲精品在线观看 | 欧美成人一区二免费视频软件 | 国产一区二区三区欧美 | 色先锋影院 | 日韩午夜电影 | 日韩三级在线观看 | 91免费黄色片 | 黄色片网站免费观看 | 成人在线小视频 | 日韩精品一区二区三区在线观看视频网站 | 亚洲免费观看在线视频 | 久久亚洲一区二区三区明星换脸 | 亚洲一区欧美 | 亚洲特黄av| 欧美3区 | 成人h动漫精品一区二区樱花 | 欧美一级片在线播放 | 久久不卡| 欧美日韩91 | 日韩欧美不卡 | 在线观看成人小视频 | 精品自拍视频在线观看 | 爱色区综合网 | 欧美在线视频日韩 | 中日韩一线二线三线视频 | 久久男人免费视频 | 99精品视频在线免费观看 | 久久精品久久久久久 | 国产毛片v一区二区三区 | 97色综合 | 欧州一区二区三区 | 色爽|