Commit 01bd4fe7 authored by yanzg's avatar yanzg

拦截器

parent e6a2add1
package com.yanzuoguang.cloud.aop;
import com.alibaba.fastjson.JSON;
import com.yanzuoguang.util.cache.MemoryCache;
import com.yanzuoguang.util.contants.ResultConstants;
import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.thread.ThreadNext;
import com.yanzuoguang.util.vo.LogVo;
import com.yanzuoguang.util.vo.ResponseResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
public class BaseRequestAspect implements ThreadNext.Next {
@Value("${spring.application.name}")
protected String applicationName;
@Value("${yzg.logAll:false}")
protected boolean logAll = false;
@Value("${yzg.cacheTime:120}")
protected int cacheTime = 120;
@Autowired
protected ApplicationContext context;
protected LogFeign logFeign;
/**
* 缓存队列
*/
protected volatile LinkedBlockingQueue<LogVo> cache = new LinkedBlockingQueue<LogVo>();
// 缓存的每次请求的结果
protected MemoryCache<RequestCacheResult> _cacheResult = new MemoryCache<>(cacheTime);
public BaseRequestAspect() {
ThreadNext.start(this, "save log error");
}
/**
* 添加日志到缓存中,并不是立即添加,而是通过线程执行,防止对环境造成影响
*
* @param logVo
*/
public void addLog(LogVo logVo) {
cache.add(logVo);
}
/**
* 初始化日志Vo
*
* @param url 请求路径
* @param joinPoint 请求参数
* @param responseResult 返回参数
* @return
*/
protected LogVo initLogInterVo(String url, ProceedingJoinPoint joinPoint, ResponseResult responseResult) {
LogVo logInterVo = new LogVo();
logInterVo.setLogId(StringHelper.getNewID());
logInterVo.setLogSources(applicationName);//平台名
logInterVo.setInterUrl(url);//请求URL
List<Object> para = new ArrayList<>();
for (Object item : joinPoint.getArgs()) {
if (item instanceof HttpServlet || item instanceof HttpServletResponse || item instanceof HttpServletRequest) {
continue;
}
para.add(item);
}
Object paraTo = para;
if (para.size() == 1) {
paraTo = para.get(0);
}
logInterVo.setContent(JSON.toJSONString(paraTo));//请求参数
logInterVo.setResult(JSON.toJSONString(responseResult));//返回参数
logInterVo.setStatus(responseResult.getCode() == ResultConstants.SUCCESS ? 1 : 0);
return logInterVo;
}
/**
* 执行下一个函数,出现异常会继续执行
*
* @return 是否继续执行
*/
@Override
public boolean next() {
while (cache.size() > 0) {
LogVo item = cache.poll();
if (item != null) {
if (logFeign == null) {
logFeign = context.getBean(LogFeign.class);
}
logFeign.save(item);
}
}
return true;
}
/**
* 沉睡时间
*
* @return
*/
@Override
public int getNextTime() {
return 1000;
}
}
...@@ -17,7 +17,7 @@ import org.springframework.stereotype.Component; ...@@ -17,7 +17,7 @@ import org.springframework.stereotype.Component;
*/ */
@Aspect @Aspect
@Component @Component
public class FeignAspect extends AbstractValidateAspect { public class FeignAspect extends HttpAspectUtil {
private static final Logger logger = LoggerFactory.getLogger(FeignAspect.class); private static final Logger logger = LoggerFactory.getLogger(FeignAspect.class);
......
...@@ -9,14 +9,14 @@ import javax.servlet.http.HttpServletRequest; ...@@ -9,14 +9,14 @@ import javax.servlet.http.HttpServletRequest;
/** /**
* 虚拟拦截类 * 虚拟拦截类
*/ */
public abstract class AbstractValidateAspect { public class HttpAspectUtil {
/** /**
* 获取 http request * 获取 http request
* *
* @return * @return
*/ */
protected static HttpServletRequest getRequest() { public static HttpServletRequest getRequest() {
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (attributes == null) { if (attributes == null) {
throw new CodeException("监视错误"); throw new CodeException("监视错误");
...@@ -29,7 +29,7 @@ public abstract class AbstractValidateAspect { ...@@ -29,7 +29,7 @@ public abstract class AbstractValidateAspect {
* *
* @return * @return
*/ */
protected static String getHttpRequestUrl() { public static String getHttpRequestUrl() {
return getRequest().getServletPath(); return getRequest().getServletPath();
} }
} }
package com.yanzuoguang.cloud.aop;
import com.yanzuoguang.util.contants.ResultConstants;
import com.yanzuoguang.util.exception.ExceptionHelper;
import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.log.Log;
import com.yanzuoguang.util.vo.LogVo;
import com.yanzuoguang.util.vo.ResponseResult;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
/**
* LogsAspect(接口请求日志切面)
*
* @author: Kang
* @time: 2018年04月25日 11:43
*/
@Aspect
@Component
public class MqAspect extends BaseRequestAspect {
private static final Logger logger = LoggerFactory.getLogger(MqAspect.class);
/**
* exec aop point aspect
*/
@Pointcut("execution(* *..mq..*Consumer.*(..))")
public void webAspect() {
}
/**
* 执行环形切面
*
* @param joinPoint
* @return
*/
@Around(value = "webAspect()")
public Object requestWebAround(ProceedingJoinPoint joinPoint) throws Throwable {
Log.threadBegin();
long start = System.currentTimeMillis();
String name = joinPoint.getSignature().getName();
try {
Object ret = executeMethod(joinPoint, name);
long end = System.currentTimeMillis();
logger.error("[ {} ] time ({})ms, result is {}", name, (end - start), ret);
return ret;
} catch (Exception e) {
long end = System.currentTimeMillis();
logger.error("[ {} ] time ({})ms, is error {}", name, (end - start), e);
// 消费消息出错
ResponseResult responseResult = ExceptionHelper.getError(e);
saveInterLogs(joinPoint, responseResult);
Log.error(joinPoint.getSignature().getDeclaringType(), e);
throw e;
} finally {
Log.threadCommit();
}
}
private Object executeMethod(ProceedingJoinPoint joinPoint, String name) throws Throwable {
return joinPoint.proceed();
}
/**
* deal with inter api logs
*
* @param joinPoint 请求参数
* @param responseResult 返回参数
*/
private void saveInterLogs(ProceedingJoinPoint joinPoint, ResponseResult responseResult) {
// 日志请求不记录,防止死循环递归
if (applicationName.indexOf("log") >= 0) {
return;
}
// 正常请求不记录
if (!logAll && responseResult.getCode() == ResultConstants.SUCCESS) {
return;
}
LogVo logVo = initLogInterVo(StringHelper.EMPTY, joinPoint, responseResult);
addLog(logVo);
}
}
package com.yanzuoguang.cloud.aop; package com.yanzuoguang.cloud.aop;
import com.alibaba.fastjson.JSON;
import com.yanzuoguang.util.cache.MemoryCache;
import com.yanzuoguang.util.contants.ResultConstants; import com.yanzuoguang.util.contants.ResultConstants;
import com.yanzuoguang.util.exception.ExceptionHelper; import com.yanzuoguang.util.exception.ExceptionHelper;
import com.yanzuoguang.util.helper.JSONHelper; import com.yanzuoguang.util.helper.JSONHelper;
import com.yanzuoguang.util.helper.StringHelper; import com.yanzuoguang.util.helper.StringHelper;
import com.yanzuoguang.util.log.Log; import com.yanzuoguang.util.log.Log;
import com.yanzuoguang.util.base.ObjectHelper; import com.yanzuoguang.util.base.ObjectHelper;
import com.yanzuoguang.util.thread.ThreadNext;
import com.yanzuoguang.util.vo.LogVo; import com.yanzuoguang.util.vo.LogVo;
import com.yanzuoguang.util.vo.ResponseResult; import com.yanzuoguang.util.vo.ResponseResult;
import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.ProceedingJoinPoint;
...@@ -19,21 +16,12 @@ import org.aspectj.lang.annotation.Pointcut; ...@@ -19,21 +16,12 @@ import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature; import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger; import org.slf4j.Logger;
import org.slf4j.LoggerFactory; import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component; import org.springframework.stereotype.Component;
import javax.servlet.ServletRequest; import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse; import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method; import java.lang.reflect.Method;
import java.lang.reflect.Type; import java.lang.reflect.Type;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.LinkedBlockingQueue;
/** /**
* LogsAspect(接口请求日志切面) * LogsAspect(接口请求日志切面)
...@@ -43,35 +31,9 @@ import java.util.concurrent.LinkedBlockingQueue; ...@@ -43,35 +31,9 @@ import java.util.concurrent.LinkedBlockingQueue;
*/ */
@Aspect @Aspect
@Component @Component
public class WebAspect extends AbstractValidateAspect implements ThreadNext.Next { public class WebAspect extends BaseRequestAspect {
private static final Logger logger = LoggerFactory.getLogger(WebAspect.class); private static final Logger logger = LoggerFactory.getLogger(BaseRequestAspect.class);
@Value("${spring.application.name}")
private String applicationName;
@Value("${yzg.logAll:false}")
private boolean logAll = false;
@Value("${yzg.cacheTime:120}")
private int cacheTime = 120;
@Autowired
private ApplicationContext context;
private LogFeign logFeign;
/**
* 缓存队列
*/
private volatile LinkedBlockingQueue<LogVo> cache = new LinkedBlockingQueue<LogVo>();
// 缓存的每次请求的结果
private MemoryCache<RequestCacheResult> _cacheResult = new MemoryCache<>(cacheTime);
public WebAspect() {
ThreadNext.start(this, "save log error");
}
/** /**
* exec aop point aspect * exec aop point aspect
...@@ -153,7 +115,7 @@ public class WebAspect extends AbstractValidateAspect implements ThreadNext.Next ...@@ -153,7 +115,7 @@ public class WebAspect extends AbstractValidateAspect implements ThreadNext.Next
// 请求编号和公司编号挂钩 // 请求编号和公司编号挂钩
reqId = StringHelper.getId(ObjectHelper.getString(firstArgs, "companyId"), reqId); reqId = StringHelper.getId(ObjectHelper.getString(firstArgs, "companyId"), reqId);
} }
String reqFull = StringHelper.getId(reqId, getHttpRequestUrl()); String reqFull = StringHelper.getId(reqId, HttpAspectUtil.getHttpRequestUrl());
RequestCacheResult req = _cacheResult.get(reqFull, new RequestCacheResult(reqFull)); RequestCacheResult req = _cacheResult.get(reqFull, new RequestCacheResult(reqFull));
// 缓存的键值对 // 缓存的键值对
if (req.getResult() == null) { if (req.getResult() == null) {
...@@ -190,75 +152,7 @@ public class WebAspect extends AbstractValidateAspect implements ThreadNext.Next ...@@ -190,75 +152,7 @@ public class WebAspect extends AbstractValidateAspect implements ThreadNext.Next
if (!logAll && responseResult.getCode() == ResultConstants.SUCCESS) { if (!logAll && responseResult.getCode() == ResultConstants.SUCCESS) {
return; return;
} }
LogVo logVo = initLogInterVo(getHttpRequestUrl(), joinPoint, responseResult); LogVo logVo = initLogInterVo(HttpAspectUtil.getHttpRequestUrl(), joinPoint, responseResult);
addLog(logVo); addLog(logVo);
} }
/**
* 添加日志到缓存中,并不是立即添加,而是通过线程执行,防止对环境造成影响
*
* @param logVo
*/
public void addLog(LogVo logVo) {
cache.add(logVo);
}
/**
* 初始化日志Vo
*
* @param url 请求路径
* @param joinPoint 请求参数
* @param responseResult 返回参数
* @return
*/
private LogVo initLogInterVo(String url, ProceedingJoinPoint joinPoint, ResponseResult responseResult) {
LogVo logInterVo = new LogVo();
logInterVo.setLogId(StringHelper.getNewID());
logInterVo.setLogSources(applicationName);//平台名
logInterVo.setInterUrl(url);//请求URL
List<Object> para = new ArrayList<>();
for (Object item : joinPoint.getArgs()) {
if (item instanceof HttpServlet || item instanceof HttpServletResponse || item instanceof HttpServletRequest) {
continue;
}
para.add(item);
}
Object paraTo = para;
if (para.size() == 1) {
paraTo = para.get(0);
}
logInterVo.setContent(JSON.toJSONString(paraTo));//请求参数
logInterVo.setResult(JSON.toJSONString(responseResult));//返回参数
logInterVo.setStatus(responseResult.getCode() == ResultConstants.SUCCESS ? 1 : 0);
return logInterVo;
}
/**
* 执行下一个函数,出现异常会继续执行
*
* @return 是否继续执行
*/
@Override
public boolean next() {
while (cache.size() > 0) {
LogVo item = cache.poll();
if (item != null) {
if (logFeign == null) {
logFeign = context.getBean(LogFeign.class);
}
logFeign.save(item);
}
}
return true;
}
/**
* 沉睡时间
*
* @return
*/
@Override
public int getNextTime() {
return 1000;
}
} }
Markdown is supported
0% or
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment