亚洲精品久久久中文字幕-亚洲精品久久片久久-亚洲精品久久青草-亚洲精品久久婷婷爱久久婷婷-亚洲精品久久午夜香蕉

您的位置:首頁技術文章
文章詳情頁

springboot實現異步調用@Async的示例

瀏覽:82日期:2023-04-04 13:11:49

在后端開發中經常遇到一些耗時或者第三方系統調用的情況,我們知道Java程序一般的執行流程是順序執行(不考慮多線程并發的情況),但是順序執行的效率肯定是無法達到我們的預期的,這時就期望可以并行執行,常規的做法是使用多線程或線程池,需要額外編寫代碼實現。在spring3.0后引入了@Async注解,使用該注解可以達到線程池的執行效果,而且在開發上非常簡單。

一、概述

springboot是基于spring框架的,在springboot環境下演示@Async注解的使用方式。先看下該注解的定義,

@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documentedpublic @interface Async { /** * A qualifier value for the specified asynchronous operation(s). * <p>May be used to determine the target executor to be used when executing this * method, matching the qualifier value (or the bean name) of a specific * {@link java.util.concurrent.Executor Executor} or * {@link org.springframework.core.task.TaskExecutor TaskExecutor} * bean definition. * <p>When specified on a class level {@code @Async} annotation, indicates that the * given executor should be used for all methods within the class. Method level use * of {@code Async#value} always overrides any value set at the class level. * @since 3.1.2 */ String value() default '';}

可以看到該注解只有一個屬性,那就是value,從注釋上知道value指定的是執行該任務的線程池,也就是說我們可以使用子定義的線程池執行我們的任務,而不是系統默認的。在看該注解上的注解,

@Target({ElementType.METHOD, ElementType.TYPE})@Retention(RetentionPolicy.RUNTIME)@Documented

也就是說該注解可以用在方法和類上。標記在類上表示類中的所有方法都以異步方式執行,也就是提交到線程池執行。

二、詳述

上面簡單對@Async注解進行了解釋,下面看用法。

1、@EnableAsync注解

在springboot中要使用@Async注解必須在springboot啟動類上使用@EnableAsync注解,開啟@Async注解的自動配置,如下,

package com.example.demo;import com.example.demo.properties.ApplicationPro;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.boot.context.properties.EnableConfigurationProperties;import org.springframework.scheduling.annotation.EnableAsync;import org.springframework.scheduling.annotation.EnableScheduling;@SpringBootApplication@EnableConfigurationProperties({ApplicationPro.class})//開啟@Async注解的自動配置@EnableAsyncpublic class DemoApplication { public static void main(String[] args) { SpringApplication.run(DemoApplication.class, args); }}

只有在啟動類上使用@EnableAsync注解,@Async注解才會生效。

2、@Async注解

上面使用@EnableAsync注解已經開啟了對@Async注解的配置,下面看具體的異步調用類,

package com.example.demo.service;import com.example.demo.Student;import org.springframework.scheduling.annotation.Async;import org.springframework.scheduling.annotation.AsyncResult;import org.springframework.stereotype.Service;import java.util.concurrent.Future;@Service@Asyncpublic class AsyncService { public Future<Student> get(){ Student stu=new Student('1','3'); try { Thread.sleep(10000l); } catch (InterruptedException e) { e.printStackTrace(); } return AsyncResult.forValue(stu); } public void executeRemote(){ try { Thread.sleep(10000l); } catch (InterruptedException e) { e.printStackTrace(); } }}

首先,要使該類讓spring管理必須使用@Service注解(或其他注解也可以),然后在類上標記@Async注解,前面說過@Async注解可以在方法或類上使用,在類上使用則表示類中的所有方法均使用異步執行的方式。異步執行類中有兩個方法,每個方法為了演示執行的耗時操作均睡眠10s。這兩個方法一個是有返回值的,另一個是無返回值的,重點看有返回值的,

public Future<Student> get(){ Student stu=new Student('1','3'); try { Thread.sleep(10000l); } catch (InterruptedException e) { e.printStackTrace(); } return AsyncResult.forValue(stu); }

為什么方法的返回值是Future,在@Async注釋上有下面這句話,

springboot實現異步調用@Async的示例

從上面的注解正好可以說明返回Future是沒問題,但是我們的方法就是一個普通的方法,要怎么才能返回Future類那,不慌,spring針對@Async注解提供了AsyncResult類,從類名就知道該類就是為了@Async注解準備的,

springboot實現異步調用@Async的示例

使用其中的forValue方法,便可以返回一個帶有泛型的Future類了。

看下測試類,

package com.example.demo.controller;import com.example.demo.Student;import com.example.demo.service.AsyncService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.stereotype.Controller;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.ResponseBody;import java.util.concurrent.ExecutionException;import java.util.concurrent.Future;@Controller@RequestMapping('async')public class ControllerAsyncTest { @Autowired private AsyncService asyncService; @RequestMapping('/test') @ResponseBody public Student get(){ try { long start=System.currentTimeMillis(); //調用帶有返回值的get方法 Future<Student> result=asyncService.get(); //調用無返回值的executeRemote方法 asyncService.executeRemote(); Student student=result.get(); long end=System.currentTimeMillis(); System.out.println('執行時間:'+(end-start)); return student; } catch (InterruptedException e) { e.printStackTrace(); } catch (ExecutionException e) { e.printStackTrace(); } return null; }}

測試類就是一個簡單的controller,調用了get和executeRemote方法,這兩個方法分別會睡眠10s,而且get會有返回值,下面看是否可以拿到get的返回值,并看下調用這兩個方法的時間,

springboot實現異步調用@Async的示例

可以成功拿到返回值,看執行時間,

2020-12-12 21:37:43.556 INFO 11780 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms執行時間:10006

執行時間是10006ms,也就是10s多,按照上面的分析兩個方法分別睡眠了10s,如果同步執行那肯定是20s,把@Async注解去掉看執行時間,

2020-12-12 21:41:07.840 INFO 11584 --- [nio-8080-exec-1] o.s.web.servlet.DispatcherServlet : Completed initialization in 5 ms執行時間:20001

執行時間是20001ms,算上兩個方法睡眠的時間,和測試類本身的時間,20001ms是沒錯的。從這里可以看出@Async注解的作用,把每個方法當作任務提交給了線程池,提高了任務執行的時間。

另外,在獲取異步的執行結果使用了下面的方法,

Future<Student> result=asyncService.get();asyncService.executeRemote();//獲得執行結果Student student=result.get();

由于在主線程要獲得任務的執行結果,使用Future類的get方法獲得結果,該結果需要等到任務執行完以后才可以獲得。

三、總結

本文講解了異步調用@Async注解的使用,

1、使用@EnableAsync注解開啟對@Async注解的支持;

2、在類或方法上使用@Async注解;

到此這篇關于springboot實現異步調用@Async的示例的文章就介紹到這了,更多相關springboot 異步調用@Async內容請搜索好吧啦網以前的文章或繼續瀏覽下面的相關文章希望大家以后多多支持好吧啦網!

標簽: Spring
相關文章:
主站蜘蛛池模板: 妞干网中文字幕 | 免费精品视频在线 | 精品无人区一区二区三区 | 色播日韩 | 日韩欧美成人免费中文字幕 | 青草伊人久久 | 欧洲成人免费高清视频 | 国产中的精品一区的 | 亚洲综合一区二区三区 | 毛片毛片毛片毛片毛片毛片 | 日本xxxx韩国护士 | 亚洲欧美日韩在线一区二区三区 | 亚洲欧美中文字幕专区 | 亚洲欧美在线一区 | 国产大片在线播放 | 欧美大片国产在线永久播放 | 岛国一级毛片 | 国产性色视频在线高清 | 手机看片日韩日韩国产在线看 | 国产精品二区三区 | 国产日韩精品一区二区在线观看播放 | 久久国产综合 | 日本免费va毛片在线看大 | 国产精品1024在线永久免费 | 在线不卡一区二区三区日韩 | 国产精品久久久久久久免费大片 | 国产欧美日韩在线观看 | 狠狠色噜噜狠狠狠狠97不卡 | 天天在线天天看成人免费视频 | 激情婷婷综合 | 国产午夜精品一二区理论影院 | 国产黄在线观看免费观看软件视频 | 欧美一级毛片免费网站 | 国产特黄一级片 | 国内在线精品 | 久操视频免费观看 | 一级特黄aaa免费 | 另类二区 | 欧美日韩中文一区 | 亚洲色图综合网站 | 深夜a级毛片免费视频 |