为了记录支付服务与其他服务的交互参数及结果
在实际业务逻辑中,需要将某些关键的场景的参数都记录下来,然而我们没有办法在每一个方法上都加上记录的代码,这个时候我们就可以使用spring中的aop,面向切面来解决这个问题。
当有任何请求调用某个或者某些接口的时候,切面切点执行在对应的controller即可。
第一步:在pom.xml文件中加入aop所需的依赖
<dependency>
<groupId>org.springframework.boot</groupId>
<artifactId>spring-boot-starter-aop</artifactId>
</dependency>
第二步:创建切面申明类
@Aspect
@Component
public class RequestAspect {
}
这有一个小疑问,为什么用了@Aspect还要加上@Component才会起作用:
官方文档中:You may register aspect classes as regular beans in your Spring XML configuration, or autodetect them through classpath scanning - just like any other Spring-managed bean. However, note that the @Aspect annotation is not sufficient for autodetection in the classpath: For that purpose, you need to add a separate @Component annotation (or alternatively a custom stereotype annotation that qualifies, as per the rules of Spring’s component scanner).
翻译为:您可以在Spring XML配置中将方面类注册为常规bean,或者通过类路径扫描自动检测它们 - 就像任何其他Spring管理的bean一样。 但是,请注意@Aspect注释不足以在类路径中自动检测:为此,您需要添加单独的@Component注释(或者根据Spring的组件扫描程序的规则添加符合条件的自定义构造型注释)。
第三步:设置切点
@Pointcut("execution(* com.khalildai.pay.controller.*.*(..)) || " +
"execution(* com.khalildai.pay.thirdpartypay.api.*.*(..))")
public void requestLog() {
}
第四步:设置通知
@Around("webLog()")
public Object arround(ProceedingJoinPoint pjp) {
// 接收到请求,记录请求内容
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
if (null == attributes) return null;
HttpServletRequest request = attributes.getRequest();
Map<String, String[]> parameterMap = request.getParameterMap();
String params;
if (parameterMap.size() == 0) {
params = Arrays.toString(pjp.getArgs());
} else {
params = JSONObject.toJSONString(parameterMap);
}
// 记录下请求内容
RequestLog requestLog = RequestLog.builder().
requestUri(request.getRequestURI()).
method(request.getMethod()).
requestTime(new Date()).
params(params).
build();
try {
Object proceed = pjp.proceed();
if (proceed instanceof GlobalResponse) {
GlobalResponse o = (GlobalResponse) proceed;
requestLog.setResult(o.toString());
requestLog.setResultCode(o.getReturnFlag());
requestLogMapper.insert(requestLog);
return o;
}
if (proceed instanceof String) {
String o = (String) proceed;
requestLog.setResult(o);
requestLog.setResultCode(o);
requestLogMapper.insert(requestLog);
return o;
}
return null;
} catch (Throwable e) {
log.error(e.getMessage());
requestLog.setResult(e.getMessage());
requestLog.setResultCode("500");
requestLogMapper.insert(requestLog);
return null;
}
}