我有简单的Spring Data JPA存储库。
public interface UserRepository extends JpaRepository<UserEntity, Serializable>{ … }
有没有办法监视Spring生成的方法的执行时间(例如findOne(…)
)?
答案 0 :(得分:9)
最简单的方法是使用CustomizableTraceInterceptor
,如下所示:
@Configuration
@EnableAspectJAutoProxy
public class SpringDataExecutionLoggingConfiguration {
@Bean
public CustomizableTraceInterceptor customizableTraceInterceptor() {
CustomizableTraceInterceptor customizableTraceInterceptor = new CustomizableTraceInterceptor();
customizableTraceInterceptor.setUseDynamicLogger(true);
customizableTraceInterceptor.setExitMessage("Executed $[methodName] in $[invocationTime]");
return customizableTraceInterceptor;
}
@Bean
public Advisor advisor() {
AspectJExpressionPointcut pointcut = new AspectJExpressionPointcut();
pointcut.setExpression("execution(public * org.springframework.data.jpa.repository.CrudRepository+.*(..))");
return new DefaultPointcutAdvisor(pointcut, customizableTraceInterceptor());
}
}
答案 1 :(得分:4)
另一个有效的解决方案:
@Aspect
@Component
public class ProfilerAspect {
Logger logger = LoggerFactory.getLogger(this.getClass());
@Pointcut("execution(public * org.springframework.data.repository.Repository+.*(..))")
public void monitor() {}
@Around("monitor()")
public Object profile(ProceedingJoinPoint pjp) {
long start = System.currentTimeMillis();
logger.debug("JVM memory in use = "+ (Runtime.getRuntime().totalMemory() - Runtime.getRuntime().freeMemory()));
Object output = null;
try {
output = pjp.proceed();
} catch (Throwable e) {
logger.error(e.getMessage(), e);
}
long elapsedTime = System.currentTimeMillis() - start;
logger.debug(pjp.getTarget()+"."+pjp.getSignature()+": Execution time: " + elapsedTime + " ms. ("+ elapsedTime/60000 + " minutes)");
return output;
}
}