springboot利⽤aop实现接⼝异步(进度条)的全过程
⽬录
⼀、前⾔
⼆、时序图
三、功能演⽰
四、关键代码
Controller
AsyncAop
AsyncService
五、源码地址
总结
⼀、前⾔
在项⽬中发现有接⼝(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", (), num, b / num));
}
AsyncAop
import util.IdUtil;
springboot aopimport com.asyf.demomon.Result;
import com.asyf.demomon.pojo.RequestHolder;
import com.asyf.demo.service.AsyncService;
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.flect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.t.request.RequestContextHolder;
import org.t.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
@Aspect
@Component
@Slf4j
public class AsyncAop {
@Autowired
private AsyncService asyncService;
@Pointcut("@annotation(com.asyf.demomon.aop.EnableAsync)")
public void costTimePointCut() {
}
@Around("costTimePointCut()")
public Object around(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//请求header
ServletRequestAttributes servletRequestAttributes = (ServletRequestAttributes) RequestAttributes(); HttpServletRequest request = Request();
RequestHolder.Header("dateFormat"));
//异步消息
String id = IdUtil.simpleUUID();
AsyncMsg asyncMsg = new AsyncMsg();
asyncMsg.setId(id);
//异步返回值
Object result = Result.success(asyncMsg);
String requestHolder = ();
//异步执⾏
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) Signature();
String className = Target().getClass().getName();
String methodName = Name();
log.info("class:{} method:{} 耗时:{}ms", className, methodName, time);
}
}
AsyncService
实现异步消息的更新
异步消息的进度信息传递通过本地线程与redis实现
import xceptions.ExceptionUtil;
import com.asyf.demomon.aop.AsyncMsg;
import com.asyf.demomon.pojo.AsyncHolder;
import com.asyf.demomon.pojo.RequestHolder;
import com.asyf.demo.service.AsyncService;
slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.RedisTemplate;
import org.springframework.stereotype.Service;
import urrent.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 = Id();
//请求线程变量-传递请求线程参数
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) {
<(ExceptionUtil.stacktraceToString(throwable));
asyncMsg.setStatus("-1");
asyncMsg.LocalizedMessage());
redisTemplate.opsForValue().set(id, asyncMsg, 60, TimeUnit.MINUTES);
}
}
}).start();
}
@Override
public void updatePercent(String per) {
AsyncMsg asyncMsg = ();
asyncMsg.setPercent(per);
redisTemplate.opsForValue().Id(), asyncMsg, 60, TimeUnit.MINUTES);
}
}
五、源码地址
java-demo: 存储代码⽰例 - Gitee
总结
到此这篇关于springboot利⽤aop实现接⼝异步(进度条)的⽂章就介绍到这了,更多相关springboot aop实现接⼝异步内容请搜索以前的⽂章或继续浏览下⾯的相关⽂章希望⼤家以后多多⽀持!
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系QQ:729038198,我们将在24小时内删除。
发表评论