springboot利用aop實現(xiàn)接口異步(進度條)的全過程
一、前言
在項目中發(fā)現(xiàn)有接口(excel導入數(shù)據(jù))處理數(shù)據(jù)需要耗時比較長的時間,是因為數(shù)據(jù)量比較大,同時數(shù)據(jù)的校驗需要耗費一定時間,決定使用一種通用的方法解決這個問題。
解決方案:通過aop使接口異步處理,前端輪詢另外一個接口查詢進度。
目標:
1接口上一個注解即可實現(xiàn)接口異步(優(yōu)化:可以通過header參數(shù)動態(tài)控制是否異步)
2一個方法實現(xiàn)進度條的更新
二、時序圖
三、功能演示
四、關鍵代碼
Controller
@EnableAsync是自已定義注解更新緩存進度asyncService.updatePercent(per);
@EnableAsync @RequestMapping(value = "test", method = RequestMethod.POST) @ApiOperation(value = "接口測試") @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); //計算百分比 String per = BigDecimal.valueOf(i).divide(BigDecimal.valueOf(15), 2, RoundingMode.HALF_DOWN).toString(); //更新redis緩存進度 asyncService.updatePercent(per); } Integer b = 100; return Result.success(String.format("線程變量值:%s,100除以%s的結果是%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(); //請求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í)行時長(毫秒) 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:{} 耗時:{}ms", className, methodName, time); } }
AsyncService
實現(xiàn)異步消息的更新
異步消息的進度信息傳遞通過本地線程與redis實現(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(); //請求線程變量-傳遞請求線程參數(shù) RequestHolder.set(requestHolder); //異步消息線程變量-傳送id到實際方法以便方法更新進度 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); } }
五、源碼地址
總結
到此這篇關于springboot利用aop實現(xiàn)接口異步(進度條)的文章就介紹到這了,更多相關springboot aop實現(xiàn)接口異步內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關文章希望大家以后多多支持腳本之家!
相關文章
關于Tomcat出現(xiàn)The origin server did not find a current represent
這篇文章主要介紹了關于Tomcat出現(xiàn)The origin server did not find a current representation for the target resourc...的問題,感興趣的小伙伴們可以參考一下2020-08-08Spring boot中自定義Json參數(shù)解析器的方法
這篇文章主要介紹了Spring boot中自定義Json參數(shù)解析器的方法,小編覺得挺不錯的,現(xiàn)在分享給大家,也給大家做個參考。一起跟隨小編過來看看吧2019-01-01Spring定時任務中@PostConstruct被多次執(zhí)行異常的分析與解決
這篇文章主要給大家介紹了關于Spring定時任務中@PostConstruct被多次執(zhí)行異常的分析與解決方法,文中通過示例代碼介紹的非常詳細,對大家的學習或者工作具有一定的參考學習價值,需要的朋友們下面隨著小編來一起學習學習吧。2017-10-10提高開發(fā)效率Live?Templates使用技巧詳解
這篇文章主要為大家介紹了提高開發(fā)效率Live?Templates使用技巧詳解,有需要的朋友可以借鑒參考下,希望能夠有所幫助,祝大家多多進步,早日升職加薪2023-01-01java實現(xiàn)百度坐標的摩卡托坐標與火星坐標轉(zhuǎn)換的示例
這篇文章主要介紹了java實現(xiàn)百度坐標的摩卡托坐標與火星坐標轉(zhuǎn)換的示例,需要的朋友可以參考下2014-03-03SpringBoot如何手寫一個starter并使用這個starter詳解
starter是SpringBoot中的一個新發(fā)明,它有效的降低了項目開發(fā)過程的復雜程度,對于簡化開發(fā)操作有著非常好的效果,下面這篇文章主要給大家介紹了關于SpringBoot如何手寫一個starter并使用這個starter的相關資料,需要的朋友可以參考下2022-12-12