package com.seecen.redis.aop;
import com.fasterxml.jackson.core.JsonProcessingException;
import com.fasterxml.jackson.databind.ObjectMapper;
import com.seecen.redis.entity.TLog;
import com.seecen.redis.mapper.TLogMapper;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Before;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Map;/**
* @author bigpeng
* @create 2020-07-22-10:17*/@Aspect
@Component
@Slf4jpublic classLogAspect {
@AutowiredprivateTLogMapper logMapper;
@AutowiredprivateRabbitTemplate rabbitTemplate;//定义切入点,使用了该注解的方法将被AOP切入
@Pointcut("@annotation( com.seecen.redis.aop.Log)")public voidlogPointCut(){}/**
* 使用前置通知来完成日志的记录
* @param joinPoint 连接点信息*/@Before("logPointCut()")public voidlogBefore(JoinPoint joinPoint) throws JsonProcessingException {
MethodSignature signature=(MethodSignature) joinPoint.getSignature();
Method method=signature.getMethod();
Log logAnnotation= method.getAnnotation(Log.class);
String type=logAnnotation.logType().getType();
String content=logAnnotation.content();//获取request对象
ServletRequestAttributes requestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request=requestAttributes.getRequest();//请求的IP地址
String ip =request.getRemoteAddr();//请求数据
Map data =request.getParameterMap();
String dataJsonStr="";if(data!=null) {
ObjectMapper objectMapper= newObjectMapper();
dataJsonStr=objectMapper.writeValueAsString(data);
}
TLog tLog= newTLog();
tLog.setContent(content);
tLog.setData(dataJsonStr);
tLog.setIp(ip);
tLog.setType(type);//log {}表示占位符
log.info("请求日志信息:{}",tLog);//插入数据库
long start =System.currentTimeMillis();
logMapper.insertSelective(tLog);
log.info("直接插入数据库耗时:{}",System.currentTimeMillis()-start);
start=System.currentTimeMillis();//发消息队列
rabbitTemplate.convertAndSend("log.exchange","aopLog",tLog);
log.info("发送mq消息耗时:{}",System.currentTimeMillis()-start);
}
}