springboot利用aop實現接口異步(進度條)的全過程

一、前言

在項目中發現有接口(excel導入數據)處理數據需要耗時比較長的時間,是因為數據量比較大,同時數據的校驗需要耗費一定時間,決定使用一種通用的方法解決這個問題。

解決方案:通過aop使接口異步處理,前端輪詢另外一個接口查詢進度。

目標:

1接口上一個註解即可實現接口異步(優化:可以通過header參數動態控制是否異步)

2一個方法實現進度條的更新

二、時序圖

三、功能演示

四、關鍵代碼

Controller

@EnableAsync是自已定義註解更新緩存進度asyncService.updatePercent(per);

    @EnableAsync
    @RequestMapping(value = "test", method = RequestMethod.POST)
    @ApiOperation(value = "接口測試")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "num", value = "數字", 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();
 
        //異步執行
        asyncService.async(requestHolder, asyncMsg, point);
 
        //執行時長(毫秒)
        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

實現異步消息的更新

異步消息的進度信息傳遞通過本地線程與redis實現

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();
                //請求線程變量-傳遞請求線程參數
                RequestHolder.set(requestHolder);
                //異步消息線程變量-傳送id到實際方法以便方法更新進度
                AsyncHolder.set(asyncMsg);
                //執行方法
                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: 存儲代碼示例 – Gitee.com

總結

到此這篇關於springboot利用aop實現接口異步(進度條)的文章就介紹到這瞭,更多相關springboot aop實現接口異步內容請搜索WalkonNet以前的文章或繼續瀏覽下面的相關文章希望大傢以後多多支持WalkonNet!

推薦閱讀: