前置知识:
Spring Boot 项目中如何使用异步任务-CSDN博客
通过AOP和Async,将日志信息异步的记录到数据库中
步骤:
-
添加依赖
<!--aop--> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-aop</artifactId> </dependency>
-
创建日志切面
/**
*
* 操作日志切面
*/
@Component
@Aspect
public class OperLogAspect {
@Resource
private OperLogService operLogService;
@Pointcut("@annotation(org.springframework.web.bind.annotation.PostMapping)" +
"||@annotation(org.springframework.web.bind.annotation.PutMapping)" +
"||@annotation(org.springframework.web.bind.annotation.DeleteMapping)")
public void pc() {
}
@Around("pc()")
public Object around(ProceedingJoinPoint joinPoint) {
HttpServletRequest request = ServletUtil.getRequest();
int businessType = 0;
switch (request.getMethod()) {
case "POST":
businessType = 1;
break;
case "PUT":
businessType = 2;
break;
case "DELETE":
businessType = 3;
break;
}
OperLog operLog = new OperLog();
operLog.setTitle(request.getRequestURI().split("/")[4]);
operLog.setBusinessType(businessType);
operLog.setMethod(joinPoint.getSignature().getName());
operLog.setRequestMethod(request.getMethod());
operLog.setOperatorType(1);
operLog.setOperName("admin"); // 通过token获取用户名
operLog.setRoleName("管理员"); // 通过token获取用户id,然后获取用户的角色
operLog.setOperUrl(request.getRequestURL().toString());
operLog.setOperIp(AddressUtil.getIpAddr(request));
operLog.setOperLocation(AddressUtil.getLocationByIp(operLog.getOperIp()));
operLog.setOperParam(Arrays.toString(joinPoint.getArgs()));
operLog.setOperTime(LocalDateTime.now());
Long start = System.currentTimeMillis();
try {
// 核心业务
Object res = joinPoint.proceed();
operLog.setJsonResult(JSONUtil.toJsonStr(res));
operLog.setStatus(0);
return res;
} catch (Throwable e) {
operLog.setJsonResult(JSONUtil.toJsonStr(AjaxResult.error(e.getMessage())));
operLog.setStatus(1);
operLog.setErrorMsg(e.getMessage());
throw new RuntimeException(e.getMessage());
}finally {
Long end = System.currentTimeMillis();
operLog.setCostTime(end-start);
// 记录操作日志
operLogService.add(operLog);
}
}
}
3.创建日志服务相关接口(entity、mapper、service)
@Service
@Transactional(rollbackFor = Exception.class)
public class OperLogServiceImpl implements OperLogService {
@Resource
private OperLogMapper operLogMapper;
/**
* 异步记录操作日志
*/
@Async
@Override
public void add(OperLog operLog) {
operLogMapper.insert(operLog);
}
}