java 监控mysql执行sql

背景

统计应用执行的sql,根据sql类型数量,进行数据库优化和sql语句优化

实现

mysql-connector-java 包中存在StatementInterceptorV2,

public class MySQLStatementInterceptor implements StatementInterceptorV2 {
    private static final Log LOGGER = LogFactory.getLog("GROUP");

    /*
     * @see com.mysql.jdbc.StatementInterceptorV2#destroy()
     */
    @Override
    public void destroy() {
        // TODO Auto-generated method stub
    }

    /*
     * @see com.mysql.jdbc.StatementInterceptorV2#executeTopLevelOnly()
     */
    @Override
    public boolean executeTopLevelOnly() {
        // TODO Auto-generated method stub
        return true;
    }

    /*
     * @see com.mysql.jdbc.StatementInterceptorV2#init(com.mysql.jdbc.Connection,
     * java.util.Properties)
     */
    @Override
    public void init(Connection arg0, Properties arg1) throws SQLException {
        LOGGER.info("执行sql:" + arg0);
        // TODO Auto-generated method stub
    }

    /*
     * @see com.mysql.jdbc.StatementInterceptorV2#postProcess(java.lang.String,
     * com.mysql.jdbc.Statement, com.mysql.jdbc.ResultSetInternalMethods,
     * com.mysql.jdbc.Connection, int, boolean, boolean, java.sql.SQLException)
     */
    @Override
    public ResultSetInternalMethods postProcess(String arg0, Statement arg1, ResultSetInternalMethods arg2,
            Connection arg3, int arg4, boolean arg5, boolean arg6, SQLException arg7) throws SQLException {
        LOGGER.info("执行sql:" + arg0);
        // TODO Auto-generated method stub
        return null;
    }

    /*
     * @see com.mysql.jdbc.StatementInterceptorV2#preProcess(java.lang.String,
     * com.mysql.jdbc.Statement, com.mysql.jdbc.Connection)
     */
    @Override
    public ResultSetInternalMethods preProcess(String arg0, Statement arg1, Connection arg2) throws SQLException {
        LOGGER.info("执行sql:" + arg0);
        // TODO Auto-generated method stub
        return null;
    }

在jdbc连接字符中后添加,a?statementInterceptors=com.github.kristofa.brave.db.MySQLStatementInterceptor

结尾

由于应用中的sql都会进行输出,使用此方法时,请留意,以免大量sql,输出,对应用产生影响。

你可能感兴趣的:(数据库)