我们在对api进行设计时,需要考虑对api的监控,监控内容包括:api调用状态、api调用时间,以及时发现问题。我们说一下用Spring拦截器进行接口监控的简单设计。
在一次请求中一些核心组件的处理步骤
1、HandlerInterceptor#preHandle
2、handle
3、HandlerInterceptor#postHandle
:如果handle过程中抛出异常,跳过这个步骤。
4、ExceptionHandlerMethodResolver#resolveException
:异常处理器,只有handle过程抛出异常时会选择相应的ExceptionHandler进行处理。
5、HandlerInterceptor#afterCompletion
:能获取到流程中任何组件抛出的异常
关于HandlerInterceptor
做接口监控的设计
我们一般使用HandlerInterceptor
做接口监控时,需要区分成功的接口和失败的接口,因为考虑到ExceptionHandler
会对异常进行处理,所以一般我们通过TreadLocal
变量或者request#setAttribute
来记录接口的调用情况,下面是一个例子:
public class ApiMonitorInterceptor implements HandlerInterceptor {
@Override
public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler)
throws Exception {
/*
用于计算api调用时间
*/
request.setAttribute(API_START_TIME_KEY, System.currentTimeMillis());
return true;
}
@Override
public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex)
throws Exception {
if (ApiStatusRecord.isSuccess()) {
/*
1、计算并记录System.currentTimeMillis() - request.getAttribute(API_START_TIME_KEY);
2、记录调用成功次数
*/
} else {
/*
记录失败次数
*/
}
}
}
public class ApiStatusRecord {
private static ThreadLocal<Boolean> status = new ThreadLocal<>();
public static void fail(){
status.set(false);
}
public static boolean isSuccess() {
boolean result = Optional.ofNullable(status.get()).orElse(true);
status.remove();
return result;
}
}
你可以在Service层中抛出异常时,调用ApiStatusRecord.fail()
记录失败状态(使用ThreadLocal
进行状态记录,可以大大降低侵入性)。