欧美bbbwbbbw肥妇,免费乱码人妻系列日韩,一级黄片

springboot利用aop實(shí)現(xiàn)接口異步(進(jìn)度條)的全過(guò)程

 更新時(shí)間:2022年01月05日 12:18:40   作者:阿瑟與非  
我們?cè)陂_(kāi)發(fā)中,調(diào)用第三方接口時(shí),往往是提交數(shù)據(jù),要異步去獲取數(shù)據(jù),下面這篇文章主要給大家介紹了關(guān)于springboot利用aop實(shí)現(xiàn)接口異步(進(jìn)度條)的相關(guān)資料,文中通過(guò)實(shí)例代碼介紹的非常詳細(xì),需要的朋友可以參考下

一、前言

在項(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)文章

最新評(píng)論