Spring Boot中使用AOP統一處理Web請求日誌
阿新 • • 發佈:2019-01-07
在spring boot中,簡單幾步,使用spring AOP實現一個攔截器:
1、引入依賴:
[html] view plain copy print?
2、建立攔截器類(在該類中,定義了攔截規則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping註解的方法。):
[java] view plain copy print?
證明攔截器已經生效。
1、引入依賴:
[html] view plain copy print?
- <dependency>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-aop</artifactId>
- </dependency>
<dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
2、建立攔截器類(在該類中,定義了攔截規則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping註解的方法。):
[java] view plain copy print?
- /**
- * 攔截器:記錄使用者操作日誌,檢查使用者是否登入……
- * @author XuJijun
- */
- @Aspect
- @Component
- publicclass ControllerInterceptor {
- privatestaticfinal Logger logger = LoggerFactory.getLogger(ControllerInterceptor.
- @Value(“${spring.profiles}”)
- private String env;
- /**
- * 定義攔截規則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping註解的方法。
- */
- @Pointcut(“execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)”)
- publicvoid controllerMethodPointcut(){}
- /**
- * 攔截器具體實現
- * @param pjp
- * @return JsonResult(被攔截方法的執行結果,或需要登入的錯誤提示。)
- */
- @Around(“controllerMethodPointcut()”) //指定攔截器規則;也可以直接把“execution(* com.xjj………)”寫進這裡
- public Object Interceptor(ProceedingJoinPoint pjp){
- long beginTime = System.currentTimeMillis();
- MethodSignature signature = (MethodSignature) pjp.getSignature();
- Method method = signature.getMethod(); //獲取被攔截的方法
- String methodName = method.getName(); //獲取被攔截的方法名
- Set<Object> allParams = new LinkedHashSet<>(); //儲存所有請求引數,用於輸出到日誌中
- logger.info(”請求開始,方法:{}”, methodName);
- Object result = null;
- Object[] args = pjp.getArgs();
- for(Object arg : args){
- //logger.debug(“arg: {}”, arg);
- if (arg instanceof Map<?, ?>) {
- //提取方法中的MAP引數,用於記錄進日誌中
- @SuppressWarnings(“unchecked”)
- Map<String, Object> map = (Map<String, Object>) arg;
- allParams.add(map);
- }elseif(arg instanceof HttpServletRequest){
- HttpServletRequest request = (HttpServletRequest) arg;
- if(isLoginRequired(method)){
- if(!isLogin(request)){
- result = new JsonResult(ResultCode.NOT_LOGIN, “該操作需要登入!去登入嗎?\n\n(不知道登入賬號?請聯絡老許。)”, null);
- }
- }
- //獲取query string 或 posted form data引數
- Map<String, String[]> paramMap = request.getParameterMap();
- if(paramMap!=null && paramMap.size()>0){
- allParams.add(paramMap);
- }
- }elseif(arg instanceof HttpServletResponse){
- //do nothing…
- }else{
- //allParams.add(arg);
- }
- }
- try {
- if(result == null){
- // 一切正常的情況下,繼續執行被攔截的方法
- result = pjp.proceed();
- }
- } catch (Throwable e) {
- logger.info(”exception: ”, e);
- result = new JsonResult(ResultCode.EXCEPTION, “發生異常:”+e.getMessage());
- }
- if(result instanceof JsonResult){
- long costMs = System.currentTimeMillis() - beginTime;
- logger.info(”{}請求結束,耗時:{}ms”, methodName, costMs);
- }
- return result;
- }
- /**
- * 判斷一個方法是否需要登入
- * @param method
- * @return
- */
- privateboolean isLoginRequired(Method method){
- if(!env.equals(“prod”)){ //只有生產環境才需要登入
- returnfalse;
- }
- boolean result = true;
- if(method.isAnnotationPresent(Permission.class)){
- result = method.getAnnotation(Permission.class).loginReqired();
- }
- return result;
- }
- //判斷是否已經登入
- privateboolean isLogin(HttpServletRequest request) {
- returntrue;
- /*String token = XWebUtils.getCookieByName(request, WebConstants.CookieName.AdminToken);
- if(“1”.equals(redisOperator.get(RedisConstants.Prefix.ADMIN_TOKEN+token))){
- return true;
- }else {
- return false;
- }*/
- }
- }
/**
* 攔截器:記錄使用者操作日誌,檢查使用者是否登入……
* @author XuJijun
*/
@Aspect
@Component
public class ControllerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);
@Value("${spring.profiles}")
private String env;
/**
* 定義攔截規則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping註解的方法。
*/
@Pointcut("execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void controllerMethodPointcut(){}
/**
* 攔截器具體實現
* @param pjp
* @return JsonResult(被攔截方法的執行結果,或需要登入的錯誤提示。)
*/
@Around("controllerMethodPointcut()") //指定攔截器規則;也可以直接把“execution(* com.xjj.........)”寫進這裡
public Object Interceptor(ProceedingJoinPoint pjp){
long beginTime = System.currentTimeMillis();
MethodSignature signature = (MethodSignature) pjp.getSignature();
Method method = signature.getMethod(); //獲取被攔截的方法
String methodName = method.getName(); //獲取被攔截的方法名
Set<Object> allParams = new LinkedHashSet<>(); //儲存所有請求引數,用於輸出到日誌中
logger.info("請求開始,方法:{}", methodName);
Object result = null;
Object[] args = pjp.getArgs();
for(Object arg : args){
//logger.debug("arg: {}", arg);
if (arg instanceof Map<?, ?>) {
//提取方法中的MAP引數,用於記錄進日誌中
@SuppressWarnings("unchecked")
Map<String, Object> map = (Map<String, Object>) arg;
allParams.add(map);
}else if(arg instanceof HttpServletRequest){
HttpServletRequest request = (HttpServletRequest) arg;
if(isLoginRequired(method)){
if(!isLogin(request)){
result = new JsonResult(ResultCode.NOT_LOGIN, "該操作需要登入!去登入嗎?\n\n(不知道登入賬號?請聯絡老許。)", null);
}
}
//獲取query string 或 posted form data引數
Map<String, String[]> paramMap = request.getParameterMap();
if(paramMap!=null && paramMap.size()>0){
allParams.add(paramMap);
}
}else if(arg instanceof HttpServletResponse){
//do nothing...
}else{
//allParams.add(arg);
}
}
try {
if(result == null){
// 一切正常的情況下,繼續執行被攔截的方法
result = pjp.proceed();
}
} catch (Throwable e) {
logger.info("exception: ", e);
result = new JsonResult(ResultCode.EXCEPTION, "發生異常:"+e.getMessage());
}
if(result instanceof JsonResult){
long costMs = System.currentTimeMillis() - beginTime;
logger.info("{}請求結束,耗時:{}ms", methodName, costMs);
}
return result;
}
/**
* 判斷一個方法是否需要登入
* @param method
* @return
*/
private boolean isLoginRequired(Method method){
if(!env.equals("prod")){ //只有生產環境才需要登入
return false;
}
boolean result = true;
if(method.isAnnotationPresent(Permission.class)){
result = method.getAnnotation(Permission.class).loginReqired();
}
return result;
}
//判斷是否已經登入
private boolean isLogin(HttpServletRequest request) {
return true;
/*String token = XWebUtils.getCookieByName(request, WebConstants.CookieName.AdminToken);
if("1".equals(redisOperator.get(RedisConstants.Prefix.ADMIN_TOKEN+token))){
return true;
}else {
return false;
}*/
}
}
3、測試
瀏覽器中輸入:http://localhost:8082/api/admin/login
測試結果:
[plain] view plain copy print?- 2016-07-26 11:58:12,057:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:58) - 請求開始,方法:login
- 2016-07-26 11:58:12,061:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:103) - login請求結束,耗時:8ms
2016-07-26 11:58:12,057:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:58) - 請求開始,方法:login
2016-07-26 11:58:12,061:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:103) - login請求結束,耗時:8ms
證明攔截器已經生效。