我有一个用例来跟踪 springboot 中方法的执行时间。如果执行时间超过特定时间,那么我需要抛出异常。我正在寻找在 java 和 springboot 中处理该问题的选项。该方法与 Redis 缓存进行交互,如下所述。此用例的重要方面还在于,应该在调用方法中没有任何错误的情况下抛出异常,但纯粹基于执行时间。
public CacheResponse getValue(String key) {
try{
return redisJedisTemplate.opsForValue().get(key);
} catch(Exception e){
LOGGER.error("{}: Error fetching data with key {} {}", className,key,e.getMessage());
return null;
}
}
你应该使用AOP来计算执行时间,然后抛出它:
下面是示例代码:
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.stereotype.Component;
@Aspect
@Component
public class ExecutionTimeAspect {
private static final long MAX_EXECUTION_TIME = 1000; // in milliseconds
@Around("execution(* com.example.yourpackage..*(..))")
public Object measureExecutionTime(ProceedingJoinPoint joinPoint) throws Throwable {
long startTime = System.currentTimeMillis();
Object result;
try {
result = joinPoint.proceed();
} finally {
long endTime = System.currentTimeMillis();
long executionTime = endTime - startTime;
if (executionTime > MAX_EXECUTION_TIME) {
throw new ExecutionTimeExceededException("Method execution exceeded the maximum allowed time of " + MAX_EXECUTION_TIME + " ms");
}
}
return result;
}
}