詳解Spring Boot中使用AOP統(tǒng)一處理Web請(qǐng)求日志
在spring boot中,簡單幾步,使用spring AOP實(shí)現(xiàn)一個(gè)攔截器:
1、引入依賴:
<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、創(chuàng)建攔截器類(在該類中,定義了攔截規(guī)則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping注解的方法。):
/**
* 攔截器:記錄用戶操作日志,檢查用戶是否登錄……
* @author XuJijun
*/
@Aspect
@Component
public class ControllerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);
@Value(“${spring.profiles}”)
private String env;
/**
* 定義攔截規(guī)則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping注解的方法。
*/
@Pointcut(“execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)”)
public void controllerMethodPointcut(){}
/**
* 攔截器具體實(shí)現(xiàn)
* @param pjp
* @return JsonResult(被攔截方法的執(zhí)行結(jié)果,或需要登錄的錯(cuò)誤提示。)
*/
@Around(“controllerMethodPointcut()”) //指定攔截器規(guī)則;也可以直接把“execution(* com.xjj………)”寫進(jìn)這里
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<>(); //保存所有請(qǐng)求參數(shù),用于輸出到日志中
logger.info(”請(qǐng)求開始,方法:{}”, methodName);
Object result = null;
Object[] args = pjp.getArgs();
for(Object arg : args){
//logger.debug(“arg: {}”, arg);
if (arg instanceof Map<?, ?>) {
//提取方法中的MAP參數(shù),用于記錄進(jìn)日志中
@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(不知道登錄賬號(hào)?請(qǐng)聯(lián)系老許。)”, null);
}
}
//獲取query string 或 posted form data參數(shù)
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){
// 一切正常的情況下,繼續(xù)執(zhí)行被攔截的方法
result = pjp.proceed();
}
} catch (Throwable e) {
logger.info(”exception: ”, e);
result = new JsonResult(ResultCode.EXCEPTION, “發(fā)生異常:”+e.getMessage());
}
if(result instanceof JsonResult){
long costMs = System.currentTimeMillis() - beginTime;
logger.info(”{}請(qǐng)求結(jié)束,耗時(shí):{}ms”, methodName, costMs);
}
return result;
}
/**
* 判斷一個(gè)方法是否需要登錄
* @param method
* @return
*/
private boolean isLoginRequired(Method method){
if(!env.equals(“prod”)){ //只有生產(chǎn)環(huán)境才需要登錄
return false;
}
boolean result = true;
if(method.isAnnotationPresent(Permission.class)){
result = method.getAnnotation(Permission.class).loginReqired();
}
return result;
}
//判斷是否已經(jīng)登錄
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;
}*/
}
}
/**
* 攔截器:記錄用戶操作日志,檢查用戶是否登錄……
* @author XuJijun
*/
@Aspect
@Component
public class ControllerInterceptor {
private static final Logger logger = LoggerFactory.getLogger(ControllerInterceptor.class);
@Value("${spring.profiles}")
private String env;
/**
* 定義攔截規(guī)則:攔截com.xjj.web.controller包下面的所有類中,有@RequestMapping注解的方法。
*/
@Pointcut("execution(* com.xjj.web.controller..*(..)) and @annotation(org.springframework.web.bind.annotation.RequestMapping)")
public void controllerMethodPointcut(){}
/**
* 攔截器具體實(shí)現(xiàn)
* @param pjp
* @return JsonResult(被攔截方法的執(zhí)行結(jié)果,或需要登錄的錯(cuò)誤提示。)
*/
@Around("controllerMethodPointcut()") //指定攔截器規(guī)則;也可以直接把“execution(* com.xjj.........)”寫進(jìn)這里
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<>(); //保存所有請(qǐng)求參數(shù),用于輸出到日志中
logger.info("請(qǐng)求開始,方法:{}", methodName);
Object result = null;
Object[] args = pjp.getArgs();
for(Object arg : args){
//logger.debug("arg: {}", arg);
if (arg instanceof Map<?, ?>) {
//提取方法中的MAP參數(shù),用于記錄進(jìn)日志中
@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(不知道登錄賬號(hào)?請(qǐng)聯(lián)系老許。)", null);
}
}
//獲取query string 或 posted form data參數(shù)
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){
// 一切正常的情況下,繼續(xù)執(zhí)行被攔截的方法
result = pjp.proceed();
}
} catch (Throwable e) {
logger.info("exception: ", e);
result = new JsonResult(ResultCode.EXCEPTION, "發(fā)生異常:"+e.getMessage());
}
if(result instanceof JsonResult){
long costMs = System.currentTimeMillis() - beginTime;
logger.info("{}請(qǐng)求結(jié)束,耗時(shí):{}ms", methodName, costMs);
}
return result;
}
/**
* 判斷一個(gè)方法是否需要登錄
* @param method
* @return
*/
private boolean isLoginRequired(Method method){
if(!env.equals("prod")){ //只有生產(chǎn)環(huán)境才需要登錄
return false;
}
boolean result = true;
if(method.isAnnotationPresent(Permission.class)){
result = method.getAnnotation(Permission.class).loginReqired();
}
return result;
}
//判斷是否已經(jīng)登錄
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、測(cè)試
瀏覽器中輸入:http://localhost:8082/api/admin/login
測(cè)試結(jié)果:
2016-07-26 11:58:12,057:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:58) - 請(qǐng)求開始,方法:login 2016-07-26 11:58:12,061:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:103) - login請(qǐng)求結(jié)束,耗時(shí):8ms
2016-07-26 11:58:12,057:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:58) - 請(qǐng)求開始,方法:login 2016-07-26 11:58:12,061:INFO http-nio-8082-exec-1 (ControllerInterceptor.java:103) - login請(qǐng)求結(jié)束,耗時(shí):8ms
證明攔截器已經(jīng)生效。
源代碼參考:https://github.com/xujijun/my-spring-boot
以上就是本文的全部內(nèi)容,希望對(duì)大家的學(xué)習(xí)有所幫助,也希望大家多多支持腳本之家。
相關(guān)文章
SpringBoot整合Servlet和Filter和Listener組件詳解
這篇文章主要介紹了SpringBoot整合Servlet和Filter和Listener組件詳解,在整合某報(bào)表插件時(shí)就需要使用Servlet,Spring Boot中對(duì)于整合這些基本的Web組件也提供了很好的支持,需要的朋友可以參考下2024-01-01
java web支持jsonp的實(shí)現(xiàn)代碼
這篇文章主要介紹了java web支持jsonp的實(shí)現(xiàn)代碼,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2018-11-11
Java之Springcloud Gateway內(nèi)置路由案例講解
這篇文章主要介紹了Java之Springcloud Gateway內(nèi)置路由案例講解,本篇文章通過簡要的案例,講解了該項(xiàng)技術(shù)的了解與使用,以下就是詳細(xì)內(nèi)容,需要的朋友可以參考下2021-08-08
mybatisplus?實(shí)現(xiàn)接口MetaObjectHandler自動(dòng)填充字段值
MetaObjectHandler是MyBatis-Plus提供的一個(gè)接口,本文主要介紹了mybatisplus?實(shí)現(xiàn)接口MetaObjectHandler自動(dòng)填充字段值,文中通過示例代碼介紹的非常詳細(xì),對(duì)大家的學(xué)習(xí)或者工作具有一定的參考學(xué)習(xí)價(jià)值,需要的朋友們下面隨著小編來一起學(xué)習(xí)學(xué)習(xí)吧2024-07-07
ASM源碼學(xué)習(xí)之ClassReader、ClassVisitor與ClassWriter詳解
這篇文章主要給大家介紹了ASM源碼之ClassReader、ClassVisitor與ClassWriter的相關(guān)資料,文中介紹的非常相信,相信對(duì)大家的學(xué)習(xí)或者工作具有一定的參考借鑒價(jià)值,有需要的朋友可以參考借鑒,下面來一起看看吧。2017-01-01
Springboot實(shí)現(xiàn)緩存預(yù)熱的方法
在系統(tǒng)啟動(dòng)之前通過預(yù)先將常用數(shù)據(jù)加載到緩存中,以提高緩存命中率和系統(tǒng)性能的過程,緩存預(yù)熱的目的是盡可能地避免緩存擊穿和緩存雪崩,這篇文章主要介紹了Springboot實(shí)現(xiàn)緩存預(yù)熱,需要的朋友可以參考下2024-03-03

