Using AOP is too convenient and especially suitable for this type of scenario.
The code is as follows, where the information to be counted is written to the log file, or it can be designed to be written into a table.
Package Com.ecsoft.interceptor;import Org.aspectj.lang.ProceedingJoinPoint;import Org.aspectj.lang.annotation.Around;import Org.aspectj.lang.annotation.Aspect;import org.aspectj.lang.reflect.MethodSignature;import Org.slf4j.Logger;import org.slf4j.LoggerFactory;import org.springframework.stereotype.Component;@Aspect@Component Public classTimeinterceptor {Private StaticLogger log = Loggerfactory.GetLogger(Timeinterceptor.class);//Service layer Statistics time slices, type must be final string type, the variables to be used in annotations can only be static constant type Public Static FinalString point ="Execution (* com.ecsoft.service). *impl.* (..)) ";/** * Statistical method execution time-consuming around surround notification * @param joinpoint * @return */ @Around(point) PublicObjectTimearound(Proceedingjoinpoint joinpoint) {//Define return object, get parameters required by methodObject obj =NULL; object[] args = Joinpoint.Getargs();LongStartTime = System.Currenttimemillis();Try{obj = Joinpoint.Proceed(args); }Catch(Throwable e) {log.Error("Statistics a Method execution time wrapping notification Error", e); }//Gets the method name of the execution LongEndTime = System.Currenttimemillis(); Methodsignature signature = (methodsignature) joinpoint.getsignature(); String methodName = signature.Getdeclaringtypename() +"."+ signature.GetName();//Print time-consuming information This.Printexectime(MethodName, StartTime, endTime);returnObj }/** * Printing method Execution time-consuming information, if more than a certain time, before printing * @param methodName * @param startTime * @param endTime */ Private void Printexectime(String MethodName,LongStartTime,LongEndTime) {LongDifftime = Endtime-starttime;//More than 1 seconds of record if(Difftime > +) {log.Info(MethodName +":"+ Difftime +": MS"); } } }
SPRINGAOP to monitor the execution time of each method in the service layer