其他分享
首页 > 其他分享> > Spring 之使用 AOP

Spring 之使用 AOP

作者:互联网

AOP使用实例:

1. 配置切面

@Component
@Aspect        //切面 : 定义了通知和切点的关系
@Slf4j
public class LogAspect{

   /**
    *  切点
    */
    @Pointcut
    public void pt(){}
    
    /**
     * 环绕通知
     * @param point
     */
    @Around("pt()")
    public Object log(ProceedingJoinPoint point){
       long beginTime = System.currentTimeMillis();
       Object result = null;
       try{
           //执行方法
           result = point.proceed();
           long time  = System.currentTimeMillis - beginTime;
           //保存日志
           record(point, time);
}catch(Throwable th){}
return result; } public void record(ProceedingJoinPoint point, long time){ MethodSignature signature = (ProceedingJoinPoint point)point.getSignature(); Method method = signature.getMethod(); //获取方法上的注解 LogAnnotation annotation = method.getAnnotation(LogAnnotation.class); //TODO 打印注解里的属性 //请求的接口名称 String className = point.getTarget().getClass.getName(); //请求的方法名称 String methodName = signature.getName(); log.info("request method:{}", className + ", " + methodName + "()"); //请求的参数 Object[] args = point.getArgs(); String params = JSON.toJSONString(args); log.info("params:{}", params); //获取Request 设置Ip地址 HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()); log.info("ip:{}", IpUtils.getIpAddr(request)); log.info("execute time:{} ms", time); } }

2. 工具类IpUtils

public class IpUtils{

     public static String getIpAddr(HttpServletRequest request){
          String ip = null, unKnow = "unknow", seperator = ",";
          int maxLength = 15;
          try{
               ip = request.getHeader("x-forwarded-for");
               if(StringUtils.isEmpty(ip) || unknow.equalsIgnoreCase(ip)){
                    ip =  request.getHeader("Proxy-Client-IP");
               }
               if(StringUtils.isEmpty(ip) || unknow.equalsIgnoreCase(ip) || ip.length == 0){
                    ip =  request.getHeader("WL-Proxy-Client-IP");
               }
               if(StringUtils.isEmpty(ip) || unknow.equalsIgnoreCase(ip)){
                    ip =  request.getHeader("HTTP_Client_IP");
               }
               if(StringUtils.isEmpty(ip) || unknow.equalsIgnoreCase(ip)){
                    ip =  request.getHeader("HTTP_X_FORWARDED_FOR");
               }
               if(StringUtils.isEmpty(ip) || unknow.equalsIgnoreCase(ip)){
                    ip =  request.getRemoteAddr();
               }
           }catch(Exception e){}

           //使用代理,获取第一个IP地址
           if(StringUtils.isEmpty(ip) && ip.length() > maxLength){
              int idx = ip.indexof(seperator);
              if(idx > 0){
                  ip = ip.substring(0, idx);
              }
           }
           return ip;
     }
}

  

标签:unknow,point,ip,使用,request,isEmpty,Spring,AOP,public
来源: https://www.cnblogs.com/yb-ken/p/15689324.html