您的位置:首页 > 数据库 > SQL

监控sql执行时间

2014-05-06 09:18 344 查看
import org.aopalliance.intercept.MethodInterceptor;

import org.aopalliance.intercept.MethodInvocation;

import org.apache.commons.lang.time.StopWatch;

import com.njhh.fmcp.log.PortalRunLog;

import com.njhh.fmcp.util.BeanMaker;

import com.njhh.fmcp.util.SystemConfigUtil;

/**

 * 监控系统dao执行时间

 * @author

 *

 */

public class SqlTimeAdvice implements MethodInterceptor{

    private PortalRunLog log = (PortalRunLog)BeanMaker.getBean("monitorLog");

    private PortalRunLog runLog = (PortalRunLog)BeanMaker.getBean("portalRunLog");

    private long time = SystemConfigUtil.getTimeThresholdKey();

    

    @Override

    public Object invoke(MethodInvocation invocation) throws Throwable {

        StopWatch clock = new StopWatch();

        // 计时开始

        clock.start();

        Object result = null;

        // 监控的类名

        String className = invocation.getMethod().getDeclaringClass().getSimpleName();

        //监控的方法名  

        String methodName = className + "." + invocation.getMethod().getName();

        try {

            //这个是我们监控的bean的执行并返回结果

            result = invocation.proceed();

        } catch (Throwable e) {

            //监控的参数

            runLog.error("数据库执行异常 , 方法名[" + methodName + "]" + " 参数:" + getString(invocation.getArguments()));

            throw e;

        }

        clock.stop(); //计时结束

        // 执行超过1秒的sql需要记录到监控日志

        if (clock.getTime() >= time){

            log.info("执行时间:" + clock.getTime() + " ms [" + methodName + "]" + " 参数:" + getString(invocation.getArguments()));

        }

        return result;  

    }

    

     public String getString(Object[] objs) {

         StringBuffer stringBuffer = new StringBuffer();

         for (Object object : objs) {

            stringBuffer.append("[").append(object.toString()).append("],");

         }

         if (stringBuffer.length() > 0){

             stringBuffer.deleteCharAt(stringBuffer.length() - 1);

         }

         return stringBuffer.toString();  

     }
}

<bean id="SqlProxyCreator"

        class="org.springframework.aop.framework.autoproxy.BeanNameAutoProxyCreator"

        p:beanNames="*Dao,*DaoImpl" p:interceptorNames="sqlTimeAdvice" />

    

    <bean id="sqlTimeAdvice" class="com.njhh.fmcp.interceptor.SqlTimeAdvice" /> 
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息