目录
1.Aop实现注解日志
1.1自定义注解
import java.lang.annotation.*;
//type代表可以放到类上,method代表可以放到方法上
@Target({ElementType.TYPE,ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface LogAnnotation {
//模块名称
String module() default "";
//操作名称
String operator() default "";
}
2.Aop日志
import com.alibaba.fastjson.JSON;
import com.cq.blog.until.HttpContextUtils;
import com.cq.blog.until.IpUtils;
import lombok.extern.slf4j.Slf4j;
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.aspectj.lang.reflect.MethodSignature;
import org.springframework.stereotype.Component;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
@Component
@Aspect //切面,定义了通知和切点的关系
@Slf4j
public class LogAspect {
//切点
@Pointcut("@annotation(com.cq.blog.common.aop.LogAnnotation)")
public void pt(){}
//环绕通知
@Around("pt()")
public Object log(ProceedingJoinPoint point) throws Throwable {
long beginTime = System.currentTimeMillis();
//执行方法
Object proceed = point.proceed();
//执行时间
long time = System.currentTimeMillis() - beginTime;
recordLog(point,time);
return proceed;
}
private void recordLog(ProceedingJoinPoint joinPoint, long time) {
MethodSignature signature = (MethodSignature) joinPoint.getSignature();
Method method = signature.getMethod();
LogAnnotation logAnnotation = method.getAnnotation(LogAnnotation.class);
log.info("=====================log start================================");
log.info("module:{}",logAnnotation.module());
log.info("operation:{}",logAnnotation.operator());
//请求的方法名
String className = joinPoint.getTarget().getClass().getName();
String methodName = signature.getName();
log.info("request method:{}",className + "." + methodName + "()");
// //请求的参数
Object[] args = joinPoint.getArgs();
String params = JSON.toJSONString(args[0]);
log.info("params:{}",params);
//获取request 设置IP地址
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
log.info("ip:{}", IpUtils.getIpAddr(request));
log.info("excute time : {} ms",time);
log.info("=====================log end================================");
}
}
3.Aop日志里面相关的utils工具类
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import javax.servlet.http.HttpServletRequest;
/**
* HttpServletRequest
*
*/
public class HttpContextUtils {
public static HttpServletRequest getHttpServletRequest() {
return ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
}
}
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import javax.servlet.http.HttpServletRequest;
/**
* 获取Ip
*
*/
@Slf4j
public class IpUtils {
/**
* 获取IP地址
* <p>
* 使用Nginx等反向代理软件, 则不能通过request.getRemoteAddr()获取IP地址
* 如果使用了多级反向代理的话,X-Forwarded-For的值并不止一个,而是一串IP地址,X-Forwarded-For中第一个非unknown的有效IP字符串,则为真实IP地址
*/
public static String getIpAddr(HttpServletRequest request) {
String ip = null, unknown = "unknown", seperator = ",";
int maxLength = 15;
try {
ip = request.getHeader("x-forwarded-for");
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || ip.length() == 0 || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("WL-Proxy-Client-IP");
}
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_CLIENT_IP");
}
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getHeader("HTTP_X_FORWARDED_FOR");
}
if (StringUtils.isEmpty(ip) || unknown.equalsIgnoreCase(ip)) {
ip = request.getRemoteAddr();
}
} catch (Exception e) {
log.error("IpUtils ERROR ", e);
}
// 使用代理,则获取第一个IP地址
if (StringUtils.isEmpty(ip) && ip.length() > maxLength) {
int idx = ip.indexOf(seperator);
if (idx > 0) {
ip = ip.substring(0, idx);
}
}
return ip;
}
/**
* 获取ip地址
*
* @return
*/
public static String getIpAddr() {
HttpServletRequest request = HttpContextUtils.getHttpServletRequest();
return getIpAddr(request);
}
4.将自定义的注解添加到接口上
5.调用接口,打印日志
-------------------------------------------------分隔符----------------------------------------------------------
2.Aop实现非日志注解
Aop注解日志和非注解日志的区别就在于定义切面的时候@Pointcut( )里面写的参数
如果是execution代表的是:controller包下所有的类,所有的方法,不限定参数类型和个数
如果是@annotation代表的是:@annotation里面写的注解类的包路径
注:注解缓存和非注解缓存和日志是一样的,修改切点@Pointcut即可
/**
* Aop实现日志
* @create : 2022/01/21 15:42
*/
@Component //扫描这个组件加入到spring容器中
@Aspect //切面,定义了通知和切点的关系
@Slf4j
public class LogAspect {
private Logger logger = LoggerFactory.getLogger(LogAspect.class);
//定义切面 controller下所有的类,所有的方法,不限定参数类型和个数
// 第一个 * 代表可以返回任何值,com.mybatisplus.controller是类名 第二个 * 是controller包下具体的类,写*代表所有
// 第三个 * 则代表类下的所有方法,括号里面的..代表可以接收任何类型的参数和任意多少的参数
@Pointcut(value = "execution( * com.mybatisplus.controller.*.*(..))")
public void myPointcut(){
}
//环绕通知,应用到myPointcut()这个切点上
@Around(value = "myPointcut()")
public Object myLogger(ProceedingJoinPoint pjp) throws Throwable {
//获取方法名
String className = pjp.getTarget().getClass().toString();
//获取类名
String methodName = pjp.getSignature().getName();
//接口执行前的传递的参数
Object[] args = pjp.getArgs();
ObjectMapper objectMapper = new ObjectMapper();
logger.info("调用前--->"+className+":"+methodName+"传递的参数为:"+ Arrays.toString(args));
//获取方法执行前的时间毫秒数
long beforeTimes = System.currentTimeMillis();
//执行方法,接口的返回值 proceed执行方法的返回值
Object proceed = pjp.proceed();
//获取方法的执行时间
long afterTimes = System.currentTimeMillis() - beforeTimes;
logger.info("调用后--->"+className+":"+methodName+"返回值:"+proceed);
log.info("执行时间---------------->"+afterTimes);
return proceed;
}
}
-------------------------------------------------分隔符----------------------------------------------------------
3.Aop实现注解缓存
import java.lang.annotation.*;
/**
* Aop实现注解缓存
*/
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Cache {
//缓存时间,不可能一直缓存在内存中
long expire() default 60 * 1000;
//缓存标识
String name() default "";
}
import com.alibaba.fastjson.JSON;
import com.cq.blog.vo.Result;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.codec.digest.DigestUtils;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.core.annotation.AliasFor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.time.Duration;
/**
* 在接口上添加注解,第一次查询的话,将查询结果放到redis,下次查询就从缓存里面获取,访问速度会大大提升
* 记得添加对应的fastjson依赖和redis依赖
*/
@Aspect
@Component
@Slf4j
public class CacheAspect {
@Autowired
private RedisTemplate<String, String> redisTemplate;
@Pointcut("@annotation(com.cq.blog.common.aop.cache.Cache)")
public void pt(){}
@Around("pt()")
public Object around(ProceedingJoinPoint pjp){
try {
Signature signature = pjp.getSignature();
//类名
String className = pjp.getTarget().getClass().getSimpleName();
//调用的方法名
String methodName = signature.getName();
Class[] parameterTypes = new Class[pjp.getArgs().length];
Object[] args = pjp.getArgs();
//参数
String params = "";
for(int i=0; i<args.length; i++) {
if(args[i] != null) {
params += JSON.toJSONString(args[i]);
parameterTypes[i] = args[i].getClass();
}else {
parameterTypes[i] = null;
}
}
if (StringUtils.isNotEmpty(params)) {
//加密 以防出现key过长以及字符转义获取不到的情况
params = DigestUtils.md5Hex(params);
}
Method method = pjp.getSignature().getDeclaringType().getMethod(methodName, parameterTypes);
//获取Cache注解
Cache annotation = method.getAnnotation(Cache.class);
//缓存过期时间
long expire = annotation.expire();
//缓存名称
String name = annotation.name();
//先从redis获取
String redisKey = name + "::" + className+"::"+methodName+"::"+params;
String redisValue = redisTemplate.opsForValue().get(redisKey);
if (StringUtils.isNotEmpty(redisValue)){
log.info("走了缓存~~~,{},{}",className,methodName);
return JSON.parseObject(redisValue, Result.class);
}
//获取执行方法,proceed执行方法的返回值
Object proceed = pjp.proceed();
//加上缓存注解的方法的返回值存入redis里面,key是由:类名和方法名和请求参数组成,values则是方法的返回值
// Duration.ofMillis是存到redis里面的过期时间
redisTemplate.opsForValue().set(redisKey,JSON.toJSONString(proceed), Duration.ofMillis(expire));
log.info("存入缓存~~~ {},{}",className,methodName);
return proceed;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return Result.fail("系统错误",-999);
}
}
Result 返回类
@Data
@AllArgsConstructor
public class Result {
private Boolean success;
private Integer code;
private String msg;
private Object data;
public static Result success(Object data){
return new Result(true,200,"success",data);
}
public static Result fail(String msg,Integer code){
return new Result(false,code,msg,null);
}
}
通过Postman访问接口,日志打印如下,第一次访问
在redis里面查看缓存
-------------------------------------------------分隔符----------------------------------------------------------
3.最新版Aop实现缓存注解
3.1自定义注解
/**
* @create : 2022/01/21 16:44
* Aop实现注解缓存
*/
//注解只能添加到方法上
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
@Documented
public @interface Cache {
//缓存标识
String name() default "";
}
3.2实现注解缓存
还是将方法的返回值放到redis里面
redis的key:类名和方法名和请求参数组成
redis的values:方法的返回值
import com.alibaba.fastjson.JSON;
import com.mybatisplus.entity.Content;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.Signature;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import java.lang.reflect.Method;
import java.time.Duration;
/**
* Aop实现注解缓存
* @create : 2022/01/21 16:49
*/
@Component
@Aspect
@Slf4j
public class CacheAspect {
@Autowired
private RedisTemplate<String,String> redisTemplate;
//切点
@Pointcut("@annotation(com.mybatisplus.aop.cache.Cache)")
public void myPointcut(){}
@Around(value = "myPointcut()")
public Object cacheToRedis(ProceedingJoinPoint pjp) throws Throwable {
try {
Signature signature = pjp.getSignature();
//类名
String className = pjp.getTarget().getClass().getSimpleName();
//调用的方法名
String methodName = signature.getName();
Class[] parameterTypes = new Class[pjp.getArgs().length];
Object[] args = pjp.getArgs();
//参数
String params = "";
for(int i=0; i<args.length; i++) {
if(args[i] != null) {
params += JSON.toJSONString(args[i]);
parameterTypes[i] = args[i].getClass();
}else {
parameterTypes[i] = null;
}
}
Method method = pjp.getSignature().getDeclaringType().getMethod(methodName, parameterTypes);
//获取Cache注解
Cache annotation = method.getAnnotation(Cache.class);
//缓存名称
String name = annotation.name();
//先从redis获取
String redisKey = name + "::" + className+"::"+methodName+"::"+params;
String redisValue = redisTemplate.opsForValue().get(redisKey);
if (StringUtils.isNotEmpty(redisValue)){
log.info("走了缓存~~~,{},{}",className,methodName);
//JSON.parseArray:将String类型的字符串转换为List<Content>的集合
return JSON.parseArray(redisValue, Content.class);
}
//获取执行方法的返回值
Object proceed = pjp.proceed();
//加上缓存注解的方法的返回值存入redis里面,key是由:类名和方法名和请求参数组成,values则是方法的返回值
// Duration.ofMillis是存到redis里面的过期时间
redisTemplate.opsForValue().set(redisKey,JSON.toJSONString(proceed), Duration.ofMillis(3*24*60*60*1000));
log.info("存入缓存~~~ {},{}",className,methodName);
return proceed;
} catch (Throwable throwable) {
throwable.printStackTrace();
}
return null;
}
}
4.Aop详细打印日志
/**
* Aop实现日志
* @create : 2022/01/21 15:42
*/
@Component //扫描这个组件加入到spring容器中
@Aspect //切面,定义了通知和切点的关系
@Slf4j
public class LogAspect {
private Logger logger = LoggerFactory.getLogger(LogAspect.class);
//定义切面 controller下所有的类,所有的方法,不限定参数类型和个数
// 第一个 * 代表可以返回任何值,com.mybatisplus.controller是类名 第二个 * 是controller包下具体的类,写*代表所有
// 第三个 * 则代表类下的所有方法,括号里面的..代表可以接收任何类型的参数和任意多少的参数
@Pointcut(value = "execution( * com.mybatisplus.controller.*.*(..))")
public void myPointcut(){
}
//ContentController下的所有方法
@Before(value = "within(com.mybatisplus.controller.ContentController)")
public void before(JoinPoint joinPoint){
// 开始打印请求日志
ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
HttpServletRequest request = attributes.getRequest();
// 打印请求相关参数
log.info("========================================== Start ==========================================");
// 打印请求 url
log.info("URL : {}", request.getRequestURL().toString());
log.info("Headers : {}",getHeaders(request.getHeaderNames(),request));
// 打印 Http method
log.info("HTTP Method : {}", request.getMethod());
// 打印调用 controller 的全路径以及执行方法
log.info("Class Method : {}.{}", joinPoint.getSignature().getDeclaringTypeName(), joinPoint.getSignature().getName());
// 打印请求的 IP
log.info("IP : {}", request.getRemoteAddr());
// 打印请求入参
log.info("Request Args : {}", getParams(joinPoint));
}
//环绕通知,应用到myPointcut()这个切点上
@Around(value = "myPointcut()")
public Object myLogger(ProceedingJoinPoint pjp) throws Throwable {
//获取方法名
String className = pjp.getTarget().getClass().toString();
//获取类名
String methodName = pjp.getSignature().getName();
//接口执行前的传递的参数
Object[] args = pjp.getArgs();
ObjectMapper objectMapper = new ObjectMapper();
logger.info("调用前--->"+className+":"+methodName+"传递的参数为:"+ Arrays.toString(args));
//获取方法执行前的时间毫秒数
long beforeTimes = System.currentTimeMillis();
//执行方法,接口的返回值 proceed执行方法的返回值
Object proceed = pjp.proceed();
//获取方法的执行时间
long afterTimes = System.currentTimeMillis() - beforeTimes;
logger.info("调用后--->"+className+":"+methodName+"返回值:"+proceed);
log.info("执行时间---------------->"+afterTimes);
return proceed;
}
@After("within(com.mybatisplus.controller.ContentController)")
public void after(){
log.info("=========================================== End ===========================================");
// 每个请求之间空一行
log.info("");
}
private String getParams(JoinPoint joinPoint) {
String params = "";
if (joinPoint.getArgs() != null && joinPoint.getArgs().length > 0) {
for (int i = 0; i < joinPoint.getArgs().length; i++) {
Object arg = joinPoint.getArgs()[i];
if ((arg instanceof HttpServletResponse) || (arg instanceof HttpServletRequest)
|| (arg instanceof MultipartFile) || (arg instanceof MultipartFile[])) {
continue;
}
try {
params += JSONObject.toJSONString(joinPoint.getArgs()[i]);
} catch (Exception e1) {
log.error(e1.getMessage());
}
}
}
return params;
}
private String getHeaders(Enumeration<String> headers, HttpServletRequest request){
Map<String,Object> headerMap = new HashMap<>(1);
while (headers.hasMoreElements()){
String key = headers.nextElement();
String val = request.getHeader(key);
headerMap.put(key,val);
}
return headerMap.size()>0?JSONObject.toJSONString(headerMap):"";
}
}