標籤:目的 moni nbsp monitor 計算 java dna 自訂屬性 email
為什麼要監控
服務化介面是提供服務的,介面正確性、穩定性是最最重要的,在保證正確的同時需要盡量提高介面回應時間。
有的團隊會有專門的工具來對系統回應時間、輸送量做監控,但如果團隊沒有這種“待遇”就需要自己來做一些工具為自己的代碼提供服務。
自己動手,豐衣足食
AOP + Annotation 簡陋實現,能達到目的
AOP : 使用環繞方式對介面攔截,在攔截介面前後記錄時間最後計算用時
Annotation : 自訂註解在介面上設定逾時時間(timeout)和逾時是否發送郵件選項(emailIfTimeout)
通過對介面實際執行時間和配置的逾時時間比較,系統可以計算出介面是否逾時,此時可使用日誌(或其他能通知到開發人員的方式)記錄具體哪個介面、什麼參數以及執行時間
註解可以提供更多的選項,來為自己介面服務,比如支援註解到類上,批量為介面設定了預設逾時時間、支援日誌中顯示的處理方法名稱 等等...
代碼實施
介面Annotation定義
/** * 介面自訂屬性 * * @author tianshu on 16/8/30 下午4:55. */@Target(value = {ElementType.METHOD})@Retention(RetentionPolicy.RUNTIME)public @interface InterfaceProperty { /** * 介面逾時時間,單位毫秒.預設值100毫秒 * @return 設定的逾時時間 */ int timeout() default 400; /** * 當介面響應逾時時,是否發送郵件.預設發送 * @return 返回ture需要發送郵件 */ boolean emailIfTimeout() default true;}
AOP實現
/** * @author tianshu on 16/1/28 下午10:35. */@Component@Aspectpublic class SystemRequestAspect { /** 日誌 */ private static final Logger LOG = LoggerFactory.getLogger(SystemRequestAspect.class); /** 介面逾時日誌 */ private static final Logger INTERFACE_TIMEOUT_LOG = LoggerFactory.getLogger("INTERFACE_TIMEOUT_LOG"); @Around(value = "execution(* com.xx.xx.xx.xx..*.*(..))", argNames="pjp") public Object validator(ProceedingJoinPoint pjp) throws Throwable { Object[] args = pjp.getArgs(); /** 攔截的方法名稱 */ String methodName = pjp.getTarget().getClass().getSimpleName() + "." + pjp.getSignature().getName(); try { long start = System.currentTimeMillis(); Object obj = pjp.proceed(args); long finish = System.currentTimeMillis(); long useTime = finish - start;
/** 介面回應時間監控 */ interfaceUseTimeMonitor(pjp.getTarget().getClass(), pjp.getSignature().getName(), args, useTime); return obj; } catch(Throwable e) {//處理你的異常 } finally {//處理其他 } } /** * 介面回應時間監控 * * @param targetClass 介面實現class * @param methodName 介面方法 * @param args 介面如參 * @param useTime 調用介面實際使用時間 */ private void interfaceUseTimeMonitor(Class targetClass, String methodName, Object[] args, long useTime) { /** 與介面註解最高用時做比較,符合條件發送郵件 */ try { Class[] classArray = new Class[args.length]; for(int i = 0; i < args.length ; ++i) { classArray[i] = args[i].getClass(); } Method method = targetClass.getMethod(methodName, classArray); if(method.isAnnotationPresent(InterfaceProperty.class)) { InterfaceProperty interfaceProperty = method.getAnnotation(InterfaceProperty.class); if(useTime >= interfaceProperty.timeout()) { if(INTERFACE_TIMEOUT_LOG.isInfoEnabled()) { INTERFACE_TIMEOUT_LOG.info("介面逾時,interface:[{}].useTime:[{}].settingUseTime:[{}].traceId:[{}]", new Object[]{targetClass.getSimpleName() + "." + methodName, useTime, interfaceProperty.timeout(), TraceUtils.getTrace()}); } } } } catch(Throwable e) { /** 監控邏輯處理錯誤什麼都不做 */ } }}
Java介面響應逾時監控