版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/sinaihalo/article/details/82883847
AOP底层,就是采用动态代理模式实现的。本文通过aop实现对dao层执行时间进行增强,打印出sql方法执行时间,可以对执行慢sql进行排查优化。
1 切面类
package com.ultrapower.nettech.obm.server.aop;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.context.annotation.EnableAspectJAutoProxy;
import org.springframework.stereotype.Component;
import com.ultrapower.nettech.obm.server.config.DataSourceContextHolder;
import com.ultrapower.nettech.obm.server.config.DataSourceType;
@Aspect
@EnableAspectJAutoProxy(proxyTargetClass=true)
@Component
public class SqlTimeAop {
@Around("execution(* com.ultrapower.nettech.obm.server.dao..*.*(..)) "
+ " and @annotation(com.ultrapower.nettech.obm.server.config.SqlTime) ")
public Object setReadDataSourceType(ProceedingJoinPoint joinPoint) {
//System.out.println("------------sqltimebefore-----------");
Object obj = null;
Object[] args = joinPoint.getArgs();
long startTime = System.currentTimeMillis();
try {
obj = joinPoint.proceed(args);
} catch (Throwable e) {
//logger.error("统计某方法执行耗时环绕通知出错", e);
}
long endTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
String methodName = signature.getDeclaringTypeName() + "." + signature.getName(); // 打印耗时的信息
this.printExecTime(methodName, startTime, endTime);
return obj;
}
private void printExecTime(String methodName, long startTime, long endTime) {
System.out.println(methodName+"执行时间:"+(endTime-startTime)+"毫秒");
}
}
2 注解类
package com.ultrapower.nettech.obm.server.config;
import java.lang.annotation.Documented;
import java.lang.annotation.ElementType;
import java.lang.annotation.Inherited;
import java.lang.annotation.Retention;
import java.lang.annotation.RetentionPolicy;
import java.lang.annotation.Target;
@Target({ElementType.METHOD, ElementType.TYPE})
@Retention(RetentionPolicy.RUNTIME)
@Inherited
@Documented
public @interface SqlTime {
}
3 aop增强方法
@SqlTime
public int updateDictStatusTable(DictStatusTable DictStatusTable){
int state = dictStatusTableMapper.updateByPrimaryKey(DictStatusTable);
return state;
}
4 测试类
@Autowired
DictStatusTableService dictStatusTableService;
@Test
public void testDictStatus(){
DictStatusTable dt = new DictStatusTable();
dt.setObjectid("2222");
dt.setObjecttype("host");
dt.setObjectname("测试");
dt.setObjectalias("IBM");
dt.setType("ceshi");
dt.setStype("marjor2");
dt.setInfo("warn");
//dt.setCtdata(new Timestamp(System.currentTimeMillis()));
//dt.setUpdata(new Timestamp(System.currentTimeMillis()));
// dictStatusTableService.addDictStatusTable(dt);
dictStatusTableService.updateDictStatusTable(dt);
//dictStatusTableService.deleteDictStatusTable("2222");
}