目录
一. 过程
1. 客户现场发现打印报告耗费时间长。接到反馈
2. 排查打印接口程序日志
3. 摘录拦截日志中接口请求参数
4. 排查接口中sql查询语句
5. 将sql中参数与请求参数进行匹配模拟查询。发现问题。
6. 异步添加索引(不锁表)。解决问题
二. 注意点
三. 总结
正文
一. 解决过程
1. 客户现场发现打印报告耗费时间长。接到反馈找到具体接口查看程序
2. 排查打印接口程序日志。通过接口访问拦截器输出的接口请求处理时间判断确定是程序处理过程发生了长耗时左侧箭头:URL ; 右侧箭头:接口执行时间
3. 摘录拦截日志中接口请求参数。上图中包含参数, 为了模拟sql查询做准备
参数:[ReportAndDcmDTO(param=001000258548805, printerId=3, manual=0, printType=1)]
4. 排查接口中sql查询语句。(其中buildReportData中也有一处调用了sql,这里进行标注)
5. 将sql中参数与请求参数进行匹配模拟查询。发现问题(查询时间处在案发现场时间是很长的,这里截取的图片是优化后的查询时间,这里标记一下)
6. 异步添加索引(不锁表)这里用到的mysql数据库
ALTER TABLE tablename
ADD INDEX 索引名称
USING BTREE (字段名称
) VISIBLE, ALGORITHM=INPLACE,LOCK=NONE;
二. 注意点
- 添加日志拦截器, 方便排查, 也可通过将日志推送到远端通过可视化工具的方式查看, 根据项目情况。(日志存储可自行百度)
package com.cloud.dcm.common.aspect;
import com.alibaba.fastjson.JSON;
import lombok.extern.slf4j.Slf4j;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.session.Session;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.http.HttpMethod;
import org.springframework.stereotype.Component;
import org.springframework.validation.BindingResult;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.multipart.MultipartFile;
import org.springframework.web.servlet.HandlerMapping;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Collection;
import java.util.Iterator;
import java.util.Map;
/**
* @ClassName: LogAspect
* @Description: 处理操作日志记录
*/
@Slf4j
@Aspect
@Component
public class LogAspect {
// 配置织入点
@Pointcut("@annotation(com.cloud.dcm.common.aspect.annotation.Log)")
public void logPointCut() {
}
// 配置织入点
@Pointcut("execution(* com.cloud.dcm.controller..*.*(..))")
public void logPointCut2() {
}
//around(和上面的方法名一样)
//统一打印接口日志
@Around("logPointCut2()")
public Object doAround(ProceedingJoinPoint joinPoint) throws Throwable {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
String uri = request.getRequestURI();
//参数过大 + 密码屏蔽
if (!(uri.endsWith("/di****s") || uri.endsWith("/pos****ata") || uri.endsWith("/login"))) {
long start = System.currentTimeMillis();
Object result = joinPoint.proceed();
long end = System.currentTimeMillis();
log.info("请求接口地址:{} ; 参数:{} ; 执行时间:{} ms!", uri, Arrays.toString(joinPoint.getArgs()), (end - start));
return result;
}else {
return joinPoint.proceed();
}
}
/**
* 处理完请求后执行
*
* @param joinPoint 切点
*/
@AfterReturning(pointcut = "logPointCut()", returning = "jsonResult")
public void doAfterReturning(JoinPoint joinPoint, Object jsonResult) {
handleLog(joinPoint, null, jsonResult);
}
/**
* 拦截异常操作
*
* @param joinPoint 切点
* @param e 异常
*/
@AfterThrowing(value = "logPointCut()", throwing = "e")
public void doAfterThrowing(JoinPoint joinPoint, Exception e) {
handleLog(joinPoint, e, null);
}
protected void handleLog(final JoinPoint joinPoint, final Exception e, Object jsonResult) {
try {
// 获得注解
Log controllerLog = getAnnotationLog(joinPoint);
if (controllerLog == null) {
return;
}
// 获取当前的用户
Subject subject = SecurityUtils.getSubject();
Session session = subject.getSession();
AdminInfoVO adminInfo = (AdminInfoVO) session.getAttribute(Const.ADMIN_IN_SESSION);
// LoginUser loginUser = SpringUtils.getBean(TokenService.class).getLoginUser(ServletUtils.getRequest());
// *========数据库日志=========*//
OperLog operLog = new OperLog();
operLog.setStatus(CodeMsg.SUCCESS.getCode());//成功为 1
// 请求的地址
String ip = IpUtils.getIpAddr(ServletUtils.getRequest());
operLog.setOperIp(ip);
operLog.setOperUrl(ServletUtils.getRequest().getRequestURI());
if (adminInfo != null) {
operLog.setOperName(adminInfo.getUserName());
}
if (e != null) {
operLog.setStatus(0);//失败
operLog.setErrorMsg(StringUtils.substring(e.getMessage(), 0, 2000));
}
// 设置方法名称
String className = joinPoint.getTarget().getClass().getName();
String methodName = joinPoint.getSignature().getName();
operLog.setMethod(className + "." + methodName + "()");
// 设置请求方式
operLog.setRequestMethod(ServletUtils.getRequest().getMethod());
// 处理设置注解上的参数
getControllerMethodDescription(joinPoint, controllerLog, operLog);
// 返回参数 如果为查询操作(10),则返回参数不保存,其余操作则保存;
if (operLog.getBusinessType().equals(10)) {
operLog.setJsonResult("");
} else {
operLog.setJsonResult(JSON.toJSONString(jsonResult));
}
// 保存数据库
AsyncManager.me().execute(AsyncFactory.recordOper(operLog));
} catch (Exception exp) {
// 记录本地异常日志
log.error("==前置通知异常==");
log.error("异常信息:{}", exp.getMessage());
exp.printStackTrace();
}
}
/**
* 获取注解中对方法的描述信息 用于Controller层注解
*
* @param log 日志
* @param operLog 操作日志
* @throws Exception
*/
public void getControllerMethodDescription(JoinPoint joinPoint, Log log, OperLog operLog) throws Exception {
// 设置action动作
operLog.setBusinessType(log.businessType().ordinal());
// 设置标题
operLog.setTitle(log.title());
// 设置操作人类别
operLog.setOperatorType(log.operatorType().ordinal());
// 是否需要保存request,参数和值
if (log.isSaveRequestData()) {
// 获取参数的信息,传入到数据库中。
setRequestValue(joinPoint, operLog);
}
}
/**
* 获取请求的参数,放到log中
*
* @param operLog 操作日志
* @throws Exception 异常
*/
private void setRequestValue(JoinPoint joinPoint, OperLog operLog) throws Exception {
String requestMethod = operLog.getRequestMethod();
if (HttpMethod.PUT.name().equals(requestMethod) || HttpMethod.POST.name().equals(requestMethod)) {
String params = argsArrayToString(joinPoint.getArgs());
operLog.setOperParam(StringUtils.substring(params, 0, 2000));
} else {
Map<?, ?> paramsMap =
(Map<?, ?>) ServletUtils.getRequest().getAttribute(HandlerMapping.URI_TEMPLATE_VARIABLES_ATTRIBUTE);
operLog.setOperParam(StringUtils.substring(paramsMap.toString(), 0, 2000));
}
}
/**
* 是否存在注解,如果存在就获取
*/
private Log getAnnotationLog(JoinPoint joinPoint) throws Exception {
Signature signature = joinPoint.getSignature();
MethodSignature methodSignature = (MethodSignature) signature;
Method method = methodSignature.getMethod();
if (method != null) {
return method.getAnnotation(Log.class);
}
return null;
}
/**
* 参数拼装
*/
private String argsArrayToString(Object[] paramsArray) {
String params = "";
if (paramsArray != null && paramsArray.length > 0) {
for (int i = 0; i < paramsArray.length; i++) {
if (StringUtils.isNotNull(paramsArray[i]) && !isFilterObject(paramsArray[i])) {
Object jsonObj = JSON.toJSON(paramsArray[i]);
params += jsonObj.toString() + " ";
}
}
}
return params.trim();
}
/**
* 判断是否需要过滤的对象。
*
* @param o 对象信息。
* @return 如果是需要过滤的对象,则返回true;否则返回false。
*/
@SuppressWarnings("rawtypes")
public boolean isFilterObject(final Object o) {
Class<?> clazz = o.getClass();
if (clazz.isArray()) {
return clazz.getComponentType().isAssignableFrom(MultipartFile.class);
} else if (Collection.class.isAssignableFrom(clazz)) {
Collection collection = (Collection) o;
for (Iterator iter = collection.iterator(); iter.hasNext(); ) {
return iter.next() instanceof MultipartFile;
}
} else if (Map.class.isAssignableFrom(clazz)) {
Map map = (Map) o;
for (Iterator iter = map.entrySet().iterator(); iter.hasNext(); ) {
Map.Entry entry = (Map.Entry) iter.next();
return entry.getValue() instanceof MultipartFile;
}
}
return o instanceof MultipartFile || o instanceof HttpServletRequest || o instanceof HttpServletResponse ||
o instanceof BindingResult;
}
}
三. 总结
- 使用拦截器拦截接口访问,打印日志。
- 添加索引(此处使用的mysql数据库,索引规则与其他数据库会有不同,不能凭经验(如使用oracle的经验)去判断给sql中查询条件添加索引是否起作用。