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实现接口异步内容请搜索以前的文章或继续浏览下面的相关文章希望大家以后多多支持!

以上是 springboot利用aop实现接口异步(进度条)的全过程 的全部内容, 来源链接: utcz.com/p/252066.html

回到顶部