利用Spring AOP自定義註解解決日誌和簽名校驗
一、需解決的問題
-
部分API有簽名引數(signature),Passport首先對簽名進行校驗,校驗通過才會執行實現方法。
第一種實現方式(Origin):在需要簽名校驗的接口裡寫校驗的程式碼,例如:
boolean isValid = accountService.validSignature(appid, signature, client_signature); if (!isValid) return ErrorUtil.buildError(ErrorUtil.ERR_CODE_COM_SING);
第二種實現方式(Spring Interception
<mvc:interceptors> <mvc:interceptor> <mvc:mapping path="/connect/share/**" /> <mvc:mapping path="/friend/**" /> <mvc:mapping path="/account/get_bind" /> <mvc:mapping path="/account/get_associate"/> <bean class="com.sogou.upd.passport.web.inteceptor.IdentityAndSecureInteceptor" /> </mvc:interceptor> </mvc:interceptors>
第三種實現方式(spring AOP):自定義註解,對需要進行簽名驗證的方法添加註解,例如:
@SecureValid @ResponseBody @RequestMapping(value = "/share/add", method = RequestMethod.POST)public Object addShare(HttpServletRequest req, HttpServletResponse res,InfoAPIRequestParams requestParams) { ... }
2. 日誌記錄功能,例如:某些介面需要記錄請求和響應,執行時間,類名,方法名等日誌資訊。也可採用以上三種方式實現。
3. 程式碼效能監控問題,例如方法呼叫時間、次數、執行緒和堆疊資訊等。這類問題在後一個專題提出解決方案,採用以上三種方式實現缺點太多。
以下是三種實現方式比較:
實現方式 | 優點 | 缺點 |
Origin |
不採用反射機制,效能最佳 |
邏輯複雜時,程式碼複用不好 需要在每個接口裡寫入相同程式碼(我太懶,就想寫幾個字母) |
Spring Inter |
非常適合對所有方法進行攔截,例如除錯時列印所有方法執行時間 類似過濾器的功能,如日誌處理、編碼轉換、許可權檢查 是AOP的子功能 |
不採用反射機制,效能有所影響 需要在xml檔案裡配置對哪些介面進行攔截,比較麻煩 |
Spring AOP |
使用方便,增加一個註解 非常靈活,可@Before,@After,@Around等 |
不採用反射機制,效能有所影響(效能對比後面詳細展示) |
二、Spring AOP 自定義註解的實現
在Maven中加入以下以依賴:
<!-- Spring AOP + AspectJ by shipengzhi --> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aop</artifactId> <version>3.0.6.RELEASE</version> </dependency> <dependency> <groupId>org.springframework</groupId> <artifactId>spring-aspects</artifactId> <version>3.0.6.RELEASE</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjrt</artifactId> <version>1.6.11</version> </dependency> <dependency> <groupId>org.aspectj</groupId> <artifactId>aspectjweaver</artifactId> <version>1.6.11</version> </dependency> <dependency> <groupId>cglib</groupId> <artifactId>cglib</artifactId> <version>2.1_3</version> </dependency> <!-- end -->
在spring-***.xml中加入spring支援,開啟aop功能
標頭檔案宣告 : xmlns:aop="http://www.springframework.org/schema/aop" http://www.springframework.org/schema/aop http://www.springframework.org/schema/aop/spring-aop-3.0.xsd <!-- 自定義AOP --> <aop:aspectj-autoproxy proxy-target-class="true"> <aop:include name="controllerAspect" /> </aop:aspectj-autoproxy> <bean id="controllerAspect" class="com.sogou.upd.passport.common.aspect.ControllerAspect"></bean> 或: <aop:aspectj-autoproxy>
編寫自定義註解。實現對方法所實現的功能進行描述,以便在通知中獲取描述資訊
/* * 校驗簽名合法性 自定義事務 */ @Target({ElementType.METHOD}) @Retention(RetentionPolicy.RUNTIME) @Documented @Inherited public @interface SecureValid { String desc() default "身份和安全驗證開始..."; }
@Target 用於描述註解的使用範圍(即:被描述的註解可以用在什麼地方),其取值有:
取值 |
描述 |
CONSTRUCTOR |
用於描述構造器(領盒飯)。 |
FIELD |
用於描述域(領盒飯)。 |
LOCAL_VARIABLE |
用於描述區域性變數(領盒飯)。 |
METHOD |
用於描述方法。 |
PACKAGE |
用於描述包(領盒飯)。 |
PARAMETER |
用於描述引數。 |
TYPE |
用於描述類或介面(甚至 enum )。 |
@Retention 用於描述註解的生命週期(即:被描述的註解在什麼範圍內有效),其取值有:
取值 |
描述 |
SOURCE |
在原始檔中有效(即原始檔保留,領盒飯)。 |
CLASS |
在 class 檔案中有效(即 class 保留,領盒飯)。 |
RUNTIME |
在執行時有效(即執行時保留)。 |
@Documented 在預設的情況下javadoc命令不會將我們的annotation生成再doc中去的,所以使用該標記就是告訴jdk讓它也將annotation生成到doc中去
@Inherited 比如有一個類A,在他上面有一個標記annotation,那麼A的子類B是否不用再次標記annotation就可以繼承得到呢,答案是肯定的
Annotation屬性值 有以下三種: 基本型別、陣列型別、列舉型別
1:基本串型別
public @interface UserdefinedAnnotation { intvalue(); String name(); String address(); } 使用: @UserdefinedAnnotation(value=123,name="wangwenjun",address="火星") public static void main(String[] args) { System.out.println("hello"); } }
如果一個annotation中只有一個屬性名字叫value,我沒在使用的時候可以給出屬性名也可以省略。
public @interface UserdefinedAnnotation { int value(); } 也可以寫成如下的形式 Java程式碼 @UserdefinedAnnotation(123) 等同於@UserdefinedAnnotation(value=123) public static void main(String[] args) { System.out.println("hello"); }
2:陣列型別 我們在自定義annotation中定義一個數組型別的屬性,程式碼如下:
-
public @interface UserdefinedAnnotation { int[] value(); } 使用: public class UseAnnotation { @UserdefinedAnnotation({123}) public static void main(String[] args) { System.out.println("hello"); } }
注意1:其中123外面的大括號是可以被省略的,因為只有一個元素,如果裡面有一個以上的元素的話,花括號是不能被省略的哦。比如{123,234}。
注意2:其中屬性名value我們在使用的時候進行了省略,那是因為他叫value,如果是其他名字我們就不可以進行省略了必須是@UserdefinedAnnotation(屬性名={123,234})這樣的格式。
3:列舉型別
public enum DateEnum { Monday,Tuesday,Wednesday,Thursday,Friday,Saturday,Sunday } 然後在定義一個annotation package com.wangwenjun.annatation.userdefined; public @interface UserdefinedAnnotation { DateEnum week(); } 使用: public class UseAnnotation { @UserdefinedAnnotation(week=DateEnum.Sunday) public static void main(String[] args) { System.out.println("hello"); } }
4:預設值
public @interface UserdefinedAnnotation { String name() default "zhangsan"; } 使用: public class UseAnnotation { @UserdefinedAnnotation() public static void main(String[] args) { System.out.println("hello"); } }
5:注意
Annotation是不可以繼承其他介面的,這一點是需要進行注意,這也是annotation的一個規定吧。
Annotation也是存在包結構的,在使用的時候直接進行匯入即可。
Annotation型別的型別只支援原聲資料型別,列舉型別和Class型別的一維陣列,其他的型別或者使用者自定義的類都是不可以作為annotation的型別,我檢視過文件並且進行過測試。
編寫操作日誌切面通知實現類
在編寫切面通知實現類之前,我們需要搞清楚我們需要哪些通知型別,是前置通知、後置通知、環繞通知或異常通知?根據我的需求,我們知道我們記錄的操作日誌有兩種情況,一種是操作成功,一種是操作失敗。操作成功時則方法肯定已經執行完成,顧我們需要實現一個後置通知;操作失敗時則說明方法出現異常無法正常執行完成,顧還需要一個異常通知。程式碼如下:
@Aspect //該註解標示該類為切面類
@Component //注入依賴 public class LogAspect { //標註該方法體為後置通知,當目標方法執行成功後執行該方法體 @AfterReturning("within(com.abchina.irms..*) && @annotation(rl)") public void addLogSuccess(JoinPoint jp, rmpfLog rl){ Object[] parames = jp.getArgs();//獲取目標方法體引數 String params = parseParames(parames); //解析目標方法體的引數 String className = jp.getTarget().getClass().toString();//獲取目標類名 className = className.substring(className.indexOf("com")); String signature = jp.getSignature().toString();//獲取目標方法簽名 String methodName = signature.substring(signature.lastIndexOf(".")+1, signature.indexOf("(")); String modelName = getModelName(className); //根據類名獲取所屬的模組 ... } //標註該方法體為異常通知,當目標方法出現異常時,執行該方法體 @AfterThrowing(pointcut="within(com.abchina.irms..*) && @annotation(rl)", throwing="ex") public void addLog(JoinPoint jp, rmpfLog rl, BusinessException ex){ ... }
有兩個相同的引數jp和rl,jp是切點物件,通過該物件可以獲取切點所切入方法所在的類,方法名、引數等資訊,具體方法可以看方法體的實現;rl則是我們的自定義註解的物件,通過該物件我們可以獲取註解中引數值,從而獲取方法的描述資訊。在異常通知中多出了一個ex引數,該引數是方法執行時所丟擲的異常,從而可以獲取相應的異常資訊。此處為我寫的自定義異常。注意:如果指定異常引數,則異常物件必須與通知所切入的方法體丟擲的異常保持一致,否則該通知不會執行。
@AfterReturning("within(com.abchina.irms..*) && @annotation(rl)")註解,是指定該方法體為後置通知,其有一個表示式引數,用來檢索符合條件的切點。該表示式指定com/abchina/irms目錄下及其所有子目錄下的所有帶有@rmpfLog註解的方法體為切點。
@AfterThrowing(pointcut="within(com.abchina.irms..*) && @annotation(rl)", throwing="ex")註解,是指定方法體為異常通知,其有一個表示式引數和一個丟擲異常引數。表示式引數與後置通知的表示式引數含義相同,而丟擲異常引數,則表示如果com/abchina/irms目錄下及其所有子目錄下的所有帶有@rmpfLog註解的方法體在執行時丟擲BusinessException異常時該通知便會執行。
AOP的基本概念:
- 切面(Aspect) :通知和切入點共同組成了切面,時間、地點和要發生的“故事”。
- 連線點(Joinpoint) :程式能夠應用通知的一個“時機”,這些“時機”就是連線點,例如方法被呼叫時、異常被丟擲時等等。
- 通知(Advice) :通知定義了切面是什麼以及何時使用。描述了切面要完成的工作和何時需要執行這個工作。
- 切入點(Pointcut) :通知定義了切面要發生的“故事”和時間,那麼切入點就定義了“故事”發生的地點,例如某個類或方法的名稱。
- 目標物件(Target Object) :即被通知的物件。
- AOP代理(AOP Proxy) 在Spring AOP中有兩種代理方式,JDK動態代理和CGLIB代理。預設情況下,TargetObject實現了介面時,則採用JDK動態代理;反之,採用CGLIB代理。
- 織入(Weaving)把切面應用到目標物件來建立新的代理物件的過程,織入一般發生在如下幾個時機:
(1)編譯時:當一個類檔案被編譯時進行織入,這需要特殊的編譯器才能做到,例如AspectJ的織入編譯器;
(2)類載入時:使用特殊的ClassLoader在目標類被載入到程式之前增強類的位元組程式碼;
(3)執行時:切面在執行的某個時刻被織入,SpringAOP就是以這種方式織入切面的,原理是使用了JDK的動態代理。
切入點表示式,Pointcut的定義包括兩個部分:Pointcut表示式(expression)和Pointcut簽名(signature)。讓我們先看看execution表示式的格式:
execution(modifier-pattern? ret-type-pattern declaring-type-pattern? name-pattern(param-pattern) throws-pattern?)
pattern分別表示修飾符匹配(modifier-pattern?)、返回值匹配(ret-type-pattern)、類路徑匹配(declaring-type-pattern?)、方法名匹配(name-pattern)、引數匹配((param-pattern))、異常型別匹配(throws-pattern?),其中後面跟著“?”的是可選項。
在各個pattern中可以使用“*”來表示匹配所有。在(param-pattern)中,可以指定具體的引數型別,多個引數間用“,”隔開,各個也可以用“*”來表示匹配任意型別的引數,如(String)表示匹配一個String引數的方法;(*,String)表示匹配有兩個引數的方法,第一個引數可以是任意型別,而第二個引數是String型別;可以用(..)表示零個或多個任意引數。
現在來看看幾個例子:
1)execution(* *(..)) 表示匹配所有方法
2)execution(public * com. savage.service.UserService.*(..)) 表示匹配com.savage.server.UserService中所有的公有方法
3)execution(* com.savage.server..*.*(..)) 表示匹配com.savage.server包及其子包下的所有方法
除了execution表示式外,還有within、this、target、args等Pointcut表示式。一個Pointcut定義由Pointcut表示式和Pointcut簽名組成,例如:
//Pointcut表示式 @Pointcut("execution(* com.savage.aop.MessageSender.*(..))") //Point簽名 private void log(){} 然後要使用所定義的Pointcut時,可以指定Pointcut簽名,如: @Before("og()") 上面的定義等同與: @Before("execution(* com.savage.aop.MessageSender.*(..))")
Pointcut定義時,還可以使用&&、||、!運算,如:
@Pointcut("logSender() || logReceiver()")
private void logMessage(){}
通知(Advice)型別
@Before 前置通知(Before advice) :在某連線點(JoinPoint)之前執行的通知,但這個通知不能阻止連線點前的執行。
@After 後通知(After advice) :當某連線點退出的時候執行的通知(不論是正常返回還是異常退出)。
@AfterReturning 返回後通知(After return advice) :在某連線點正常完成後執行的通知,不包括丟擲異常的情況。
@Around 環繞通知(Around advice) :包圍一個連線點的通知,類似Web中Servlet規範中的Filter的doFilter方法。可以在方法的呼叫前後完成自定義的行為,也可以選擇不執行。
@AfterThrowing 丟擲異常後通知(After throwing advice) : 在方法丟擲異常退出時執行的通知。
自定義註解實現在Controller層面
/** * 對Controller進行安全和身份校驗 */ @Around("within(@org.springframework.stereotype.Controller *) && @annotation(is)") public Object validIdentityAndSecure(ProceedingJoinPoint pjp, SecureValid is) throws Exception { Object[] args = pjp.getArgs(); //Controller中所有方法的引數,前兩個分別為:Request,Response HttpServletRequest request = (HttpServletRequest) args[0]; // HttpServletResponse response = (HttpServletResponse)args[1]; String appid = request.getParameter("appid"); int app_id = Integer.valueOf(appid); String signature = request.getParameter("signature"); String clientSignature = request.getParameter("client_signature"); String uri = request.getRequestURI(); String provider = request.getParameter("provider"); if (StringUtils.isEmpty(provider)) { provider = "passport"; } // 對appid和signature進行校驗 try { appService.validateAppid(app_id); boolean isValid = accountService.validSignature(app_id, signature, clientSignature); if (!isValid) throw new ProblemException(ErrorUtil.ERR_CODE_COM_SING); } catch (Exception e) { return handleException(e, provider, uri); } // 繼續執行接下來的程式碼 Object retVal = null; try { retVal = pjp.proceed(); } catch (Throwable e) { if (e instanceof Exception) { return handleException((Exception) e, provider, uri); } } // 目前的介面走不到這裡 return retVal; }
三、Spring攔截器的實現
在spring-***.xml中加入攔截器的配置
編寫攔截器實現類
public class CostTimeInteceptor extends HandlerInterceptorAdapter { private static final Logger log = LoggerFactory.getLogger(CostTimeInteceptor.class); @Override public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception { long startTime = System.currentTimeMillis(); request.setAttribute("startTime", startTime); return true; } @Override public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception { long startTime = (Long) request.getAttribute("startTime"); long endTime = System.currentTimeMillis(); long executeTime = endTime - startTime; if (log.isInfoEnabled()) { log.info("[" + request.getRequestURI() + "] executeTime : " + executeTime + "ms"); } } }
四、效能對比
實驗環境:對/account/get_associate介面,併發500,壓測10分鐘
指標 | Origin | Spring Inter | Spring AOP |
CPU | user%:26.57
sys%:10.97 cpu%:37.541 |
user%:26.246
sys%:10.805 cpu%:37.051 |
user%:24.123 sys%:9.938 cpu%:34.062 |
Load | 13.85 | 13.92 | 12.21 |
QPS | 6169 | 6093.2 | 5813.27 |
RT |
0.242ms |
0.242ms |
0.235ms |
採用AOP對響應時間無明顯影響
採用AOP對Load無明顯影響
採用AOP對CPU無明顯影響
結論:使用AOP效能方面影響可忽略