经过一天的开发调试终于搞懂了接口调用耗时并保存到数据库,并且保存到另外一个数据库,相当于双数据源 本功能共两个文件,一个java文件和一个数据库配置文件(HuTool jdbc读取数据库配置,相当轻量级的) 直接上代码 package com.hoskeeper.aop; import cn.hutool.db.Entity; import cn.hutool.db.SqlRunner; import cn.hutool.db.ds.DSFactory; import com.hoskeeper.data.util.DateTimeUtil; import com.hoskeeper.data.util.UUIdUtil; import org.aspectj.lang.ProceedingJoinPoint; import org.aspectj.lang.annotation.Around; import org.aspectj.lang.annotation.Aspect; import org.springframework.stereotype.Component; import org.springframework.web.context.request.RequestContextHolder; import org.springframework.web.context.request.ServletRequestAttributes; import javax.servlet.http.HttpServletRequest; import javax.sql.DataSource; import java.util.Arrays; /** * 使用Aspect统计API接口调用耗时 * @author liuzhichao * @Date 2018-08-07 * */ @Aspect @Component public class AspectAPIMoinitor { DataSource ds = ds = DSFactory.get(); SqlRunner runner = SqlRunner.create(ds); /** * 统计API接口调用耗时(方法调用的时间) * @param joinPoint * @throws Throwable */ @Around("execution(public * com.hoskeeper.controller.*.*(..))") public Object logServiceMethodAccess(ProceedingJoinPoint joinPoint) throws Throwable { // 接收到请求,记录请求内容 ServletRequestAttributes attributes = (ServletRequestAttributes) RequestContextHolder.getRequestAttributes(); HttpServletRequest request = attributes.getRequest(); long start = System.currentTimeMillis(); Object object = joinPoint.proceed(); long end = System.currentTimeMillis(); long takeTime = end - start; String className = joinPoint.getSignature().toString(); //接口监控保存 //interfaceMonitorService.insert(interfaceMonitor); //runner既SqlRunner对象 int count = runner.insert(Entity.create("t_interface_monitor") .set("monitor_id", UUIdUtil.get32UUID()) .set("request_url", request.getRequestURL().toString()) .set("request_token", request.getHeader("token")) .set("http_method", request.getMethod()) .set("class_name", className) .set("reqest_paras", Arrays.toString(joinPoint.getArgs())) .set("take_time", takeTime) .set("create_time", DateTimeUtil.now()) .set("module_name", "666")); return object; } }
=====================================================================
# ------------------------------------------------------------- # ----- Setting File with UTF8----- # ----- 数据库配置文件 ----- # ------------------------------------------------------------- url = jdbc:mysql://localhost:3306/training user = root pass = 123456 ## 可选配置 # 是否在日志中显示执行的SQL showSql = true # 是否格式化显示的SQL formatSql = false # 是否显示SQL参数 showParams = true
有问题请联系我qq:365319883