設計模式Proxy Pattern升級aop
阿新 • • 發佈:2018-12-12
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");
}