HAP_接口监控(注解)

image.png

方法一:注解:

新建注解接口:

package wht.ora20796.aop;

import java.lang.annotation.*;

/**
 * Service注解
 */
@Inherited
@Target({ElementType.METHOD})
@Retention(RetentionPolicy.RUNTIME)
public @interface ServiceAnnotation {
    String apiName() default "";
    String sysName() default "";
}

新建切面类监听注解接口:


image.png
image.png


package wht.ora20796.aop;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.hand.hap.intergration.annotation.HapInbound;
import com.hand.hap.intergration.annotation.HapOutbound;
import com.hand.hap.intergration.aop.HapInvokeAspect;
import com.hand.hap.intergration.beans.HapInvokeInfo;
import com.hand.hap.intergration.beans.HapinterfaceBound;
import com.hand.hap.intergration.dto.HapInterfaceInbound;
import com.hand.hap.intergration.dto.HapInterfaceOutbound;
import com.hand.hap.intergration.util.HapInvokeLogUtils;
import com.hand.hap.message.IMessagePublisher;
import com.hand.hap.system.dto.ResponseData;
import net.sf.json.JSONObject;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.ApplicationContext;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;
import java.util.Date;

/**
* 切面类
*/
@Component
@Aspect  // 指定当前类为切面类
public class VendorAop {
  private static final Logger logger = LoggerFactory.getLogger(HapInvokeAspect.class);
  @Autowired
  private IMessagePublisher messagePublisher;
  @Autowired
  private ObjectMapper objectMapper;
  private Class interfaceHeaderServiceClazz;
  private Class interfaceHeaderClazz;
  private Object interfaceHeaderServiceImpl;

  public VendorAop() {
  }

  public void contextInitialized(ApplicationContext applicationContext) {
      try {
          this.interfaceHeaderServiceClazz = Class.forName("com.hand.hap.intergration.service.IHapInterfaceHeaderService");
          if (this.interfaceHeaderServiceClazz != null) {
              this.interfaceHeaderClazz = Class.forName("com.hand.hap.intergration.dto.HapInterfaceHeader");
              this.interfaceHeaderServiceImpl = applicationContext.getParentBeanFactory().getBean("hapInterfaceHeaderServiceImpl", this.interfaceHeaderServiceClazz);
          }
      } catch (Exception var3) {
          logger.debug("interface module class not found");
      }

  }
//    @HapOutbound
//    HapInvokeAspect hapInvokeAspect;
  //指定切入点表单式:拦截哪些方法:即为哪些类生成代理对象
 //@Pointcut("execution(* wht.ora20796.service.ISoapVendorService.*(..))")
  @Pointcut("@annotation(wht.ora20796.aop.ServiceAnnotation)")
  public void pointCut_() {
  }
  @Around("@annotation(bound)")
  public Object aroundMethod(ProceedingJoinPoint pjd, ServiceAnnotation bound) throws Throwable {
      System.out.println("-------------------注解监听------------------");
      Long startTime = System.currentTimeMillis();
      Object result = null;
      Throwable throwable = null;
      HapInterfaceOutbound outbound = new HapInterfaceOutbound();
      HapInvokeInfo.OUTBOUND.set(outbound);
      boolean var18 = false;

      HapinterfaceBound hapinterfaceBound;
      label165: {
          try {
              var18 = true;
              outbound.setRequestTime(new Date());
              Object[] args = pjd.getArgs();
              String sysName = null;
              String apiName = null;
              Object[] var10 = args;
              int var11 = args.length;

              for(int var12 = 0; var12 < var11; ++var12) {
                  Object obj = var10[var12];
                  if (obj instanceof HttpServletRequest) {
                      sysName = ((HttpServletRequest)obj).getParameter("sysName");
                      apiName = ((HttpServletRequest)obj).getParameter("apiName");
                  }
              }

              if (sysName == null && apiName == null) {
                  sysName = bound.sysName();
                  apiName = bound.apiName();
              }

              outbound.setInterfaceName(sysName + "-" + apiName);
              if (this.interfaceHeaderServiceClazz != null && this.interfaceHeaderClazz != null && this.interfaceHeaderServiceImpl != null) {
                  Method getHeaderAndLineMethod = this.interfaceHeaderServiceClazz.getMethod("getHeaderAndLine", String.class, String.class);
                  Object hapInterfaceHeaderObject = getHeaderAndLineMethod.invoke(this.interfaceHeaderServiceImpl, sysName, apiName);
                  if (hapInterfaceHeaderObject != null) {
                      Method getDomainUrl = this.interfaceHeaderClazz.getMethod("getDomainUrl");
                      Method getIftUrl = this.interfaceHeaderClazz.getMethod("getIftUrl");
                      outbound.setInterfaceUrl(getDomainUrl.invoke(hapInterfaceHeaderObject).toString() + getIftUrl.invoke(hapInterfaceHeaderObject).toString());
                  } else {
                      outbound.setInterfaceUrl(" ");
                  }
              }

              result = pjd.proceed();
              if (HapInvokeInfo.OUTBOUND_REQUEST_PARAMETER.get() != null) {
                  outbound.setRequestParameter((String)HapInvokeInfo.OUTBOUND_REQUEST_PARAMETER.get());
              }

              if (HapInvokeInfo.HTTP_RESPONSE_CODE.get() != null) {
                  outbound.setResponseCode(((Integer)HapInvokeInfo.HTTP_RESPONSE_CODE.get()).toString());
              }

              if (HapInvokeInfo.OUTBOUND_RESPONSE_DATA.get() != null) {
                  outbound.setResponseContent((String)HapInvokeInfo.OUTBOUND_RESPONSE_DATA.get());
              } else if (result != null) {
                  outbound.setResponseContent(result.toString());
              }

              outbound.setRequestStatus("success");
              HapInterfaceInbound inbound = (HapInterfaceInbound)HapInvokeInfo.INBOUND.get();
              if (inbound != null) {
                  if (inbound.getStackTrace() != null) {
                      outbound.setStackTrace(inbound.getStackTrace());
                      outbound.setRequestStatus("failure");
                  }

                  HapInvokeInfo.INBOUND.remove();
                  var18 = false;
              } else {
                  var18 = false;
              }
              break label165;
          } catch (Throwable var19) {
              throwable = var19;
              result = new JSONObject();
              ((JSONObject)result).put("error", var19.getMessage());
              var18 = false;
          } finally {
              if (var18) {
                  outbound.setResponseTime(System.currentTimeMillis() - startTime);
                  HapInvokeLogUtils.processExceptionInfo(outbound, throwable);
                   hapinterfaceBound = new HapinterfaceBound(outbound);
                  this.messagePublisher.message("invoke.service", hapinterfaceBound);
                  HapInvokeInfo.clearOutboundInfo();
              }
          }

          outbound.setResponseTime(System.currentTimeMillis() - startTime);
          HapInvokeLogUtils.processExceptionInfo(outbound, throwable);
          hapinterfaceBound = new HapinterfaceBound(outbound);
          this.messagePublisher.message("invoke.service", hapinterfaceBound);
          HapInvokeInfo.clearOutboundInfo();
          return result;
      }

      outbound.setResponseTime(System.currentTimeMillis() - startTime);
      HapInvokeLogUtils.processExceptionInfo(outbound, throwable);
      hapinterfaceBound = new HapinterfaceBound(outbound);
      this.messagePublisher.message("invoke.service", hapinterfaceBound);
      HapInvokeInfo.clearOutboundInfo();
      return result;
  }

  // 环绕通知:环绕目标方式执行
  /*@Around("@annotation(bound)")
  public void around(ProceedingJoinPoint pjp,ServiceAnnotation bound) throws Throwable {
      System.out.println("环绕前....");
      pjp.proceed();  // 执行目标方法
      System.out.println("环绕后....");
  }*/

  // 前置通知 : 在执行目标方法之前执行
/*  @Before("pointCut_()")
  public void begin() {
      System.out.println("-----------ISoapVendorService---------");
      System.out.println("开始事务/异常");

  }

  // 后置/最终通知:在执行目标方法之后执行  【无论是否出现异常最终都会执行】
  @After("pointCut_()")
  public void after() {
      System.out.println("-----------ISoapVendorService---------");
      System.out.println("提交事务/关闭");
  }*/
/*
  // 返回后通知: 在调用目标方法结束后执行 【出现异常不执行】
  @AfterReturning("pointCut_()")
  public void afterReturning() {
      System.out.println("afterReturning()");
  }

  // 异常通知: 当目标方法执行异常时候执行此关注点代码
  @AfterThrowing("pointCut_()")
  public void afterThrowing() {
      System.out.println("afterThrowing()");
  }
*/



}

给方法添加新建的注解:


image.png

测试:


image.png
image.png

方法二:(非注解)对ISoapVendorService.java中的方法继续切面增强

package wht.ora20796.aop;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.springframework.stereotype.Component;

/**
 * 切面类
 */
@Component
@Aspect  // 指定当前类为切面类
public class VendorAop {
    //指定切入点表单式:拦截哪些方法:即为哪些类生成代理对象
    @Pointcut("execution(* wht.ora20796.service.ISoapVendorService.*(..))")
    //@Pointcut("execution(* wht.ora20796.aop.UserDaoImpl.save(..))")
    public void pointCut_() {
    }

    // 前置通知 : 在执行目标方法之前执行
    @Before("pointCut_()")
    public void begin() {
        System.out.println("-----------ISoapVendorService---------");
        System.out.println("开始事务/异常");

    }

    /*// 后置/最终通知:在执行目标方法之后执行  【无论是否出现异常最终都会执行】
    @After("pointCut_()")
    public void after() {
        System.out.println("提交事务/关闭");
    }

    // 返回后通知: 在调用目标方法结束后执行 【出现异常不执行】
    @AfterReturning("pointCut_()")
    public void afterReturning() {
        System.out.println("afterReturning()");
    }

    // 异常通知: 当目标方法执行异常时候执行此关注点代码
    @AfterThrowing("pointCut_()")
    public void afterThrowing() {
        System.out.println("afterThrowing()");
    }

    // 环绕通知:环绕目标方式执行
    @Around("pointCut_()")
    public void around(ProceedingJoinPoint pjp) throws Throwable {
        System.out.println("环绕前....");
        pjp.proceed();  // 执行目标方法
        System.out.println("环绕后....");
    }*/


}

效果:


image.png
image.png

你可能感兴趣的:(HAP_接口监控(注解))