最新国产好看的视频,伊人天堂AV在线,国产Aaaaaa视频,蜜臀视频在线观看一区,人妻av色图,密臀久久久精品影片,青青视频免费观看毛片,久草在线观看视,国产三级精品色情在线

詳解Spring Boot 異步執(zhí)行方法

 更新時間:2018年03月27日 16:54:16   作者:Simeone_xu  
這篇文章主要介紹了Spring Boot 異步執(zhí)行方法,小編覺得挺不錯的,現在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧

最近遇到一個需求,就是當服務器接到請求并不需要任務執(zhí)行完成才返回結果,可以立即返回結果,讓任務異步的去執(zhí)行。開始考慮是直接啟一個新的線程去執(zhí)行任務或者把任務提交到一個線程池去執(zhí)行,這兩種方法都是可以的。但是 Spring 這么強大,肯定有什么更簡單的方法,就 google 了一下,還真有呢。就是使用 @EnableAsync 和 @Async 這兩個注解就 ok 了。

給方法加上 @Async 注解

package me.deweixu.aysncdemo.service;

public interface AsyncService {

 void asyncMethod(String arg);
}

package me.deweixu.aysncdemo.service.ipml;

import me.deweixu.aysncdemo.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncServiceImpl implements AsyncService {

 @Async
 @Override
 public void asyncMethod(String arg) {
  System.out.println("arg:" + arg);
  System.out.println("=====" + Thread.currentThread().getName() + "=========");
 }
}

@EnableAsync

在啟動類或者配置類加上 @EnableAsync 注解

package me.deweixu.aysncdemo;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.scheduling.annotation.EnableAsync;

@EnableAsync
@SpringBootApplication
public class AysncDemoApplication {

 public static void main(String[] args) {
  SpringApplication.run(AysncDemoApplication.class, args);
 }
}

測試

package me.deweixu.aysncdemo;

import me.deweixu.aysncdemo.service.AsyncService;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;

@RunWith(SpringRunner.class)
@SpringBootTest
public class AysncDemoApplicationTests {

 @Autowired
 AsyncService asyncService;

 @Test
 public void testAsync() {
  System.out.println("=====" + Thread.currentThread().getName() + "=========");
  asyncService.asyncMethod("Async");
 }

}

=====main=========
2018-03-25 21:30:31.391  INFO 28742 --- [           main] .s.a.AnnotationAsyncExecutionInterceptor : No task executor bean found for async processing: no bean of type TaskExecutor and no bean named 'taskExecutor' either
arg:Async
=====SimpleAsyncTaskExecutor-1=========

從上面的結果看 asyncService.asyncMethod("Async") 確實異步執(zhí)行了,它使用了一個新的線程。

指定 Executor

從上面執(zhí)行的日志可以猜測到 Spring 默認使用 SimpleAsyncTaskExecutor 來異步執(zhí)行任務的,可以搜索到這個類。@Async 也可以指定自定義的 Executor。

在啟動類中增加自定義的 Executor

package me.deweixu.aysncdemo;
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.context.annotation.Bean;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.scheduling.concurrent.ThreadPoolTaskExecutor;
import java.util.concurrent.Executor;
@EnableAsync
@SpringBootApplication
public class AysncDemoApplication {

 public static void main(String[] args) {
  SpringApplication.run(AysncDemoApplication.class, args);
 }

 @Bean(name = "threadPoolTaskExecutor")
 public Executor threadPoolTaskExecutor() {
  return new ThreadPoolTaskExecutor();
 }
}

指定 Executor

package me.deweixu.aysncdemo.service.ipml;
import me.deweixu.aysncdemo.service.AsyncService;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

@Service
public class AsyncServiceImpl implements AsyncService {

 @Async("threadPoolTaskExecutor")
 @Override
 public void asyncMethod(String arg) {
  System.out.println("arg:" + arg);
  System.out.println("=====" + Thread.currentThread().getName() + "=========");
 }
}

這樣在異步執(zhí)行任務的時候就使用 threadPoolTaskExecutor

設置默認的 Executor

上面提到如果 @Async 不指定 Executor 就默認使用 SimpleAsyncTaskExecutor,其實默認的 Executor 是可以使用 AsyncConfigurer 接口來配置的

@Configuration
public class SpringAsyncConfig implements AsyncConfigurer {  
 @Override
 public Executor getAsyncExecutor() {
  return new ThreadPoolTaskExecutor();
 }  
}

異常捕獲

在異步執(zhí)行的方法中是可能出現異常的,我們可以在任務內部使用 try catch 來處理異常,當任務拋出異常時,Spring 也提供了捕獲它的方法。

實現 AsyncUncaughtExceptionHandler 接口

public class CustomAsyncExceptionHandler
 implements AsyncUncaughtExceptionHandler {
 
 @Override
 public void handleUncaughtException(
  Throwable throwable, Method method, Object... obj) { 
  System.out.println("Exception message - " + throwable.getMessage());
  System.out.println("Method name - " + method.getName());
  for (Object param : obj) {
   System.out.println("Parameter value - " + param);
  }
 }  
}

實現 AsyncConfigurer 接口重寫 getAsyncUncaughtExceptionHandler 方法

@Configuration
public class SpringAsyncConfig implements AsyncConfigurer {
  
 @Override
 public Executor getAsyncExecutor() {
  return new ThreadPoolTaskExecutor();
 }
 
 @Override
 public AsyncUncaughtExceptionHandler getAsyncUncaughtExceptionHandler() {
  return new CustomAsyncExceptionHandler();
 }

  
}

改寫 asyncMethod 方法使它拋出異常

 @Async
 @Override
 public void asyncMethod(String arg) {
  System.out.println("arg:" + arg);
  System.out.println("=====" + Thread.currentThread().getName() + "=========");
  throw new NullPointerException();
 }

運行結果:

=====main=========
arg:Async
=====threadPoolTaskExecutor-1=========
Exception message - Async NullPointerException
Method name - asyncMethod
Parameter value - Async

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

相關文章

  • 利用Java搭建個簡單的Netty通信實例教程

    利用Java搭建個簡單的Netty通信實例教程

    這篇文章主要給大家介紹了關于如何利用Java搭建個簡單的Netty通信,文中通過示例代碼介紹的非常詳細,對大家學習或者使用Java具有一定的參考學習價值,需要的朋友們下面來一起學習學習吧
    2020-05-05
  • Java線程組操作實例分析

    Java線程組操作實例分析

    這篇文章主要介紹了Java線程組操作,結合實例形式分析了ThreadGroup類創(chuàng)建與使用線程組相關操作技巧,需要的朋友可以參考下
    2019-09-09
  • springboot解決java.lang.ArrayStoreException異常

    springboot解決java.lang.ArrayStoreException異常

    這篇文章介紹了springboot解決java.lang.ArrayStoreException異常的方法,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧
    2021-12-12
  • SpringBoot3集成swagger文檔的使用方法

    SpringBoot3集成swagger文檔的使用方法

    本文介紹了Swagger的誕生背景、主要功能以及如何在Spring Boot 3中集成Swagger文檔,Swagger可以幫助自動生成API文檔,實現與代碼同步,并提供交互式測試功能,使用方法包括導入依賴、配置文檔、使用常見注解以及訪問生成的Swagger UI和文檔,感興趣的朋友跟隨小編一起看看吧
    2025-01-01
  • Java虛擬機之對象創(chuàng)建過程與類加載機制及雙親委派模型

    Java虛擬機之對象創(chuàng)建過程與類加載機制及雙親委派模型

    這篇文章主要給大家介紹了關于Java虛擬機之對象創(chuàng)建過程與類加載機制及雙親委派模型的相關資料,本文通過示例代碼以及圖文介紹的非常詳細,對大家學習或者使用java具有一定的參考學習價值,需要的朋友可以參考下
    2021-11-11
  • JavaWeb開發(fā)之使用jQuery與Ajax實現動態(tài)聯級菜單效果

    JavaWeb開發(fā)之使用jQuery與Ajax實現動態(tài)聯級菜單效果

    這篇文章主要介紹了JavaWeb開發(fā)之使用jQuery與Ajax實現動態(tài)聯級菜單效果的相關資料,非常不錯,具有參考借鑒價值,需要的朋友可以參考下
    2016-10-10
  • JAVA 枚舉單例模式及源碼分析的實例詳解

    JAVA 枚舉單例模式及源碼分析的實例詳解

    這篇文章主要介紹了 JAVA 枚舉單例模式及源碼分析的實例詳解的相關資料,需要的朋友可以參考下
    2017-08-08
  • java去除if...else的七種方法總結

    java去除if...else的七種方法總結

    相信小伙伴一定看過多篇怎么去掉?if...else?的文章,也知道大家都很有心得,知道多種方法來去掉?if...else?,本文為大家整理了7個常用的方法,希望對大家有所幫助
    2023-11-11
  • Java公平鎖與非公平鎖的核心原理講解

    Java公平鎖與非公平鎖的核心原理講解

    從公平的角度來說,Java 中的鎖總共可分為兩類:公平鎖和非公平鎖。但公平鎖和非公平鎖有哪些區(qū)別?核心原理是什么?本文就來和大家詳細聊聊
    2022-11-11
  • Java實現序列化與反序列化的簡單示例

    Java實現序列化與反序列化的簡單示例

    序列化與反序列化是指Java對象與字節(jié)序列的相互轉換,一般在保存或傳輸字節(jié)序列的時候會用到,下面有兩個Java實現序列化與反序列化的簡單示例,不過還是先來看看序列和反序列化的具體概念:
    2016-05-05

最新評論

东兰县| 龙川县| 浦江县| 杭锦后旗| 乌拉特前旗| 驻马店市| 海阳市| 福州市| 佛学| 吴川市| 军事| 响水县| 蒙自县| 抚远县| 荣昌县| 阿瓦提县| 临安市| 鹤峰县| 竹溪县| 上高县| 武穴市| 汕头市| 樟树市| 泰和县| 新巴尔虎右旗| 平凉市| 梧州市| 孟津县| 中方县| 溧阳市| 木里| 邹城市| 唐河县| 屏边| 南岸区| 五华县| 东丰县| 紫阳县| 罗定市| 固原市| 漯河市|