springboot利用aop實(shí)現(xiàn)接口異步(進(jìn)度條)的全過(guò)程
一、前言
在項(xiàng)目中發(fā)現(xiàn)有接口(excel導(dǎo)入數(shù)據(jù))處理數(shù)據(jù)需要耗時(shí)比較長(zhǎng)的時(shí)間,是因?yàn)閿?shù)據(jù)量比較大,同時(shí)數(shù)據(jù)的校驗(yàn)需要耗費(fèi)一定時(shí)間,決定使用一種通用的方法解決這個(gè)問(wèn)題。
解決方案:通過(guò)aop使接口異步處理,前端輪詢(xún)另外一個(gè)接口查詢(xún)進(jìn)度。
目標(biāo):
1接口上一個(gè)注解即可實(shí)現(xiàn)接口異步(優(yōu)化:可以通過(guò)header參數(shù)動(dòng)態(tài)控制是否異步)
2一個(gè)方法實(shí)現(xiàn)進(jìn)度條的更新
二、時(shí)序圖
三、功能演示
四、關(guān)鍵代碼
Controller
@EnableAsync是自已定義注解更新緩存進(jìn)度asyncService.updatePercent(per);
@EnableAsync @RequestMapping(value = "test", method = RequestMethod.POST) @ApiOperation(value = "接口測(cè)試") @ApiImplicitParams({ @ApiImplicitParam(name = "num", value = "數(shù)字", required = true, dataType = "int", paramType = "query", defaultValue = "1") }) public Object demo(Integer num) throws InterruptedException { for (int i = 0; i < 15; i++) { Thread.sleep(1000); //計(jì)算百分比 String per = BigDecimal.valueOf(i).divide(BigDecimal.valueOf(15), 2, RoundingMode.HALF_DOWN).toString(); //更新redis緩存進(jìn)度 asyncService.updatePercent(per); } Integer b = 100; return Result.success(String.format("線(xiàn)程變量值:%s,100除以%s的結(jié)果是%s", RequestHolder.get(), num, b / num)); }
AsyncAop
import cn.hutool.core.util.IdUtil; import com.asyf.demo.common.Result; import com.asyf.demo.common.pojo.RequestHolder; import com.asyf.demo.service.AsyncService; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.aspectj.lang.annotation.Pointcut; import org.aspectj.lang.reflect.MethodSignature; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; @Aspect @Component @Slf4j public class AsyncAop { @Autowired private AsyncService asyncService; @Pointcut("@annotation(com.asyf.demo.common.aop.EnableAsync)") public void costTimePointCut() { } @Around("costTimePointCut()") public Object around(ProceedingJoinPoint point) throws Throwable { long beginTime = System.currentTimeMillis(); //請(qǐng)求header ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = servletRequestAttributes.getRequest(); RequestHolder.set(request.getHeader("dateFormat")); //異步消息 String id = IdUtil.simpleUUID(); AsyncMsg asyncMsg = new AsyncMsg(); asyncMsg.setId(id); //異步返回值 Object result = Result.success(asyncMsg); String requestHolder = RequestHolder.get(); //異步執(zhí)行 asyncService.async(requestHolder, asyncMsg, point); //執(zhí)行時(shí)長(zhǎng)(毫秒) long time = System.currentTimeMillis() - beginTime; logCostTime(point, time); return result; } private void logCostTime(ProceedingJoinPoint point, long time) { MethodSignature signature = (MethodSignature) point.getSignature(); String className = point.getTarget().getClass().getName(); String methodName = signature.getName(); log.info("class:{} method:{} 耗時(shí):{}ms", className, methodName, time); } }
AsyncService
實(shí)現(xiàn)異步消息的更新
異步消息的進(jìn)度信息傳遞通過(guò)本地線(xiàn)程與redis實(shí)現(xiàn)
import cn.hutool.core.exceptions.ExceptionUtil; import com.asyf.demo.common.aop.AsyncMsg; import com.asyf.demo.common.pojo.AsyncHolder; import com.asyf.demo.common.pojo.RequestHolder; import com.asyf.demo.service.AsyncService; import lombok.extern.slf4j.Slf4j; import org.aspectj.lang.ProceedingJoinPoint; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.data.redis.core.RedisTemplate; import org.springframework.stereotype.Service; import java.util.concurrent.TimeUnit; @Service @Slf4j public class AsyncServiceImpl implements AsyncService { @Autowired private RedisTemplate redisTemplate; @Override public void async(String requestHolder, AsyncMsg asyncMsg, ProceedingJoinPoint point) { new Thread(new Runnable() { @Override public void run() { String id = asyncMsg.getId(); //請(qǐng)求線(xiàn)程變量-傳遞請(qǐng)求線(xiàn)程參數(shù) RequestHolder.set(requestHolder); //異步消息線(xiàn)程變量-傳送id到實(shí)際方法以便方法更新進(jìn)度 AsyncHolder.set(asyncMsg); //執(zhí)行方法 try { redisTemplate.opsForValue().set(id, asyncMsg, 60, TimeUnit.MINUTES); Object result = point.proceed(); asyncMsg.setResult(result); asyncMsg.setStatus("0"); redisTemplate.opsForValue().set(id, asyncMsg, 60, TimeUnit.MINUTES); } catch (Throwable throwable) { log.error(ExceptionUtil.stacktraceToString(throwable)); asyncMsg.setStatus("-1"); asyncMsg.setResult(throwable.getLocalizedMessage()); redisTemplate.opsForValue().set(id, asyncMsg, 60, TimeUnit.MINUTES); } } }).start(); } @Override public void updatePercent(String per) { AsyncMsg asyncMsg = AsyncHolder.get(); asyncMsg.setPercent(per); redisTemplate.opsForValue().set(asyncMsg.getId(), asyncMsg, 60, TimeUnit.MINUTES); } }
五、源碼地址
java-demo: 存儲(chǔ)代碼示例 - Gitee.com
總結(jié)
到此這篇關(guān)于springboot利用aop實(shí)現(xiàn)接口異步(進(jìn)度條)的文章就介紹到這了,更多相關(guān)springboot aop實(shí)現(xiàn)接口異步內(nèi)容請(qǐng)搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
關(guān)于Tomcat出現(xiàn)The origin server did not find a current represent
這篇文章主要介紹了關(guān)于Tomcat出現(xiàn)The origin server did not find a current representation for the target resourc...的問(wèn)題,感興趣的小伙伴們可以參考一下2020-08-08java使用ArrayList遍歷及效率比較實(shí)例分析
這篇文章主要介紹了java使用ArrayList遍歷及效率比較,實(shí)例分析了ArrayList遍歷的方法與使用技巧,具有一定參考借鑒價(jià)值,需要的朋友可以參考下2015-07-07Spring boot中自定義Json參數(shù)解析器的方法
這篇文章主要介紹了Spring boot中自定義Json參數(shù)解析器的方法,小編覺(jué)得挺不錯(cuò)的,現(xiàn)在分享給大家,也給大家做個(gè)參考。一起跟隨小編過(guò)來(lái)看看吧2019-01-01Spring定時(shí)任務(wù)中@PostConstruct被多次執(zhí)行異常的分析與解決
這篇文章主要給大家介紹了關(guān)于Spring定時(shí)任務(wù)中@PostConstruct被多次執(zhí)行異常的分析與解決方法,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來(lái)一起學(xué)習(xí)學(xué)習(xí)吧。2017-10-10提高開(kāi)發(fā)效率Live?Templates使用技巧詳解
這篇文章主要為大家介紹了提高開(kāi)發(fā)效率Live?Templates使用技巧詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進(jìn)步,早日升職加薪2023-01-01java實(shí)現(xiàn)百度坐標(biāo)的摩卡托坐標(biāo)與火星坐標(biāo)轉(zhuǎn)換的示例
這篇文章主要介紹了java實(shí)現(xiàn)百度坐標(biāo)的摩卡托坐標(biāo)與火星坐標(biāo)轉(zhuǎn)換的示例,需要的朋友可以參考下2014-03-03基于jenkins構(gòu)建結(jié)果企業(yè)微信提醒
這篇文章主要介紹了基于jenkins構(gòu)建結(jié)果企業(yè)微信提醒,文中通過(guò)示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友可以參考下2020-08-08SpringBoot如何手寫(xiě)一個(gè)starter并使用這個(gè)starter詳解
starter是SpringBoot中的一個(gè)新發(fā)明,它有效的降低了項(xiàng)目開(kāi)發(fā)過(guò)程的復(fù)雜程度,對(duì)于簡(jiǎn)化開(kāi)發(fā)操作有著非常好的效果,下面這篇文章主要給大家介紹了關(guān)于SpringBoot如何手寫(xiě)一個(gè)starter并使用這個(gè)starter的相關(guān)資料,需要的朋友可以參考下2022-12-12