国产成人精品亚洲777人妖,欧美日韩精品一区视频,最新亚洲国产,国产乱码精品一区二区亚洲

您的位置:首頁技術(shù)文章
文章詳情頁

springboot實現(xiàn)異步任務(wù)

瀏覽:3日期:2023-03-08 11:26:03

本文實例為大家分享了springboot實現(xiàn)異步任務(wù)的具體代碼,供大家參考,具體內(nèi)容如下

1.什么異步任務(wù)

同步:一定要等任務(wù)執(zhí)行完了,得到結(jié)果,才執(zhí)行下一個任務(wù)。異步:不等任務(wù)執(zhí)行完,直接執(zhí)行下一個任務(wù)。

2.異步任務(wù)使用場景

在許多網(wǎng)站中,都會有發(fā)送郵件驗證郵箱功能,執(zhí)行該任務(wù)時,需要較長的時間,此時為了更好的用戶體驗,前端可以先返回完成的信息,后臺去執(zhí)行任務(wù)。

3.異步任務(wù)的實現(xiàn)步驟

首先模擬一個網(wǎng)站跳轉(zhuǎn)的過程,假設(shè)某一個線程執(zhí)行任務(wù)時需要5秒,結(jié)束以后才會進行下一步操作,我們令線程休眠五秒,然后通過controller進行頁面跳轉(zhuǎn)

service

package com.kuang.service;import org.springframework.scheduling.annotation.Async;import org.springframework.stereotype.Service;@Servicepublic class AsyncService { @Async public void hello(){try { Thread.sleep(5000);} catch (InterruptedException e) { e.printStackTrace();}System.out.println('數(shù)據(jù)正在傳送!'); }}

controller

package com.kuang.controller;import com.kuang.service.AsyncService;import org.springframework.beans.factory.annotation.Autowired;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RestControllerpublic class AsyncController { @Autowired AsyncService asyncService; @RequestMapping('/hello') public String hello(){asyncService.hello();return 'OK'; }}總結(jié):

SpringBoot則可以使用更簡便的方式來實現(xiàn)異步任務(wù)調(diào)度。我們只需要在Service層需要多線程處理的方法上加上@Async注解。

springboot實現(xiàn)異步任務(wù)

然后在主啟動類上加上**@EnableAsync**注解來開啟異步注解功能即可執(zhí)行異步任務(wù)調(diào)度,此時執(zhí)行可立即跳轉(zhuǎn)然后再執(zhí)行hello方法控制臺來輸出“數(shù)據(jù)正在傳送”。

springboot實現(xiàn)異步任務(wù)

以上就是本文的全部內(nèi)容,希望對大家的學(xué)習(xí)有所幫助,也希望大家多多支持好吧啦網(wǎng)。

標(biāo)簽: Spring
相關(guān)文章:
主站蜘蛛池模板: 华坪县| 龙门县| 宜良县| 盘锦市| 从江县| 甘泉县| 西乌珠穆沁旗| 淮滨县| 永和县| 绥化市| 桂东县| 浮梁县| 桦甸市| 贵南县| 商城县| 乐昌市| 三穗县| 康乐县| 玉树县| 闵行区| 通化市| 海伦市| 万年县| 逊克县| 繁峙县| 微博| 乌拉特中旗| 平陆县| 兴安县| 时尚| 德兴市| 张家界市| 前郭尔| 佳木斯市| 醴陵市| 德州市| 都昌县| 万年县| 北宁市| 长寿区| 白玉县|