1定义注解
package com.xxx.common.log;
import java.lang.annotation.*;
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface UserOperateLog{
/**
* 模块
*/
String module();
/**
* 业务功能
*/
String businessType();
/**
* 是否保存请求参数
*/
boolean isSaveRequestData() default true;
/**
* 是否保存响应数据
*/
boolean isSaveResponseData() default true;
}
2 设置aop
package com.xxx.core.aop;
import java.util.concurrent.Executor;
@Aspect
public class UserOperateLogAspect extends AbstractOperateLog {
private Executor defaultExecutor;
private UserOperateLogService userOperateLogService;
private ThreadLocal<Long> startMs = new ThreadLocal<>();
public UserOperateLogAspect(Executor defaultExecutor, UserOperateLogService userOperateLogService) {
this.defaultExecutor = defaultExecutor;
this.userOperateLogService = userOperateLogService;
}
@Before("@annotation(com.chint.common.log.UserOperateLog)")
public void before() {
startMs.set(System.currentTimeMillis());
}
@AfterReturning(value = "@annotation(userOperateLog)", returning = "resultUtil")
public void doAfterReturning(JoinPoint joinPoint, UserOperateLog userOperateLog, ResultUtil<?> resultUtil) {
this.sendToMessageQueue(joinPoint, userOperateLog, resultUtil);
}
@AfterThrowing(value = "@annotation(userOperateLog)")
public void doAfterThrowing(JoinPoint joinPoint, UserOperateLog userOperateLog) {
this.sendToMessageQueue(joinPoint, userOperateLog, null);
}
private void sendToMessageQueue(JoinPoint joinPoint, UserOperateLog userOperateLog, ResultUtil<?> resultUtil) {
final UserOperateLogDO operateLogDO = new UserOperateLogDO();
final Object currentUser = ServletUtil.getCurrentUser();
if (currentUser instanceof UserDO) {
operateLogDO.setUserId(((UserDO) currentUser).getId());
}
operateLogDO.setModule(userOperateLog.module());
operateLogDO.setBusinessType(userOperateLog.businessType());
operateLogDO.setResponseStatus(resultUtil != null ? resultUtil.getStatus() : 400);
assignment(operateLogDO, joinPoint, resultUtil, userOperateLog.isSaveRequestData(), userOperateLog.isSaveResponseData());
operateLogDO.setExecuteMs((int) (System.currentTimeMillis() - startMs.get()));
defaultExecutor.execute(() -> userOperateLogService.sendToMessageQueue(operateLogDO));
startMs.remove();
}
}
3 在需要的接口上标注注解
@PutMapping("company/brand")
@ApiOperation("更新商家商标")
@UserOperateLog(module = CompanyModule.MODULE, businessType = CompanyModule.BusinessType.COMPANY_BRAND)
public ResultUtil<MessageEnum> updateCompanyBrand(@Validated UpdateCompanyBrandQuery query) {
companyService.updateCompanyBrand(query);
return ResultUtil.success(MessageEnum.UPDATE_SUCCESS);
}