用jamon来监控你的sql执行效率
/**
*作者:张荣华
*日期:2008-2-25
**/
之前有一篇文章讲到如何使用jamon来监控请求以及方法得调用(原文地址见:[url]http://www.iteye.com/post/354575 [/url]),本文属于其姊妹篇,使用jamon监控系统的sql调用及其调用效率。
需求:
1我们知道在使用hibernate得时候,我们可以打开show sql选项,可以直接查看sql语句调用的情况,那么当我们使用其他持久技术的时候我们也需要这个功能怎么办呢,没有关系,jamon能够帮我们做到。
2 很多时候,不同的程序员会写出不同的性能的sql,有时候可能会不小心或者因为不知道而写出性能很差的sql,我自己曾经就发生过这种事情,在500w条数据的表里使用了一个limit来分页,到后面,执行一条sql都需要几分钟,诸如此类的时候可能大家都有碰到过,如果能有监控sql性能的工具嵌在应用里该多好,当然有jamon就可以帮我们做到。
对于jamon来说,每一个query的执行之后的统计结果都会被保存下来,这些概要统计都以MonProxy-SQL开头。这些统计中包括查询执行的时间,有比如平均时间,执行总时间,最小执行时间,最大执行时间,这些东西难道不是我们正想要的吗。
那么让我们开始吧,我们知道,这些query执行的统计应该是在connection中被统计的,也就是说我们要代理一般的connection,而connection又是由datasource产生的,所以我们可以代理datasource,说干就干。
一个datasource接口中关于connection的方法只有两个:
/** * <p>Attempts to establish a connection with the data source that * this <code>DataSource</code> object represents. * * @return a connection to the data source * @exception SQLException if a database access error occurs */ Connection getConnection() throws SQLException; /** * <p>Attempts to establish a connection with the data source that * this <code>DataSource</code> object represents. * * @param username the database user on whose behalf the connection is * being made * @param password the user's password * @return a connection to the data source * @exception SQLException if a database access error occurs * @since 1.4 */ Connection getConnection(String username, String password) throws SQLException;
/** * @author ahuaxuan(aaron zhang) * @since 2008-2-25 * @version $Id$ */public class MonitorDataSource implements DataSource {public DataSource realDataSource;public void setRealDataSource(DataSource realDataSource) {this.realDataSource = realDataSource;}public DataSource getRealDataSource() {return realDataSource;}public Connection getConnection() throws SQLException {//表示由jamon来代理realDataSource返回的Connectionreturn MonProxyFactory.monitor(realDataSource.getConnection());}public Connection getConnection(String username, String password)throws SQLException {//表示由jamon来代理realDataSource返回的Connectionreturn MonProxyFactory.monitor(realDataSource.getConnection(username,password));}}<bean id="writeMonitorDataSource" destroy-method="close"><property name="realDataSource" ref="writeDataSource"/></bean>
<bean id="writeDataSource" destroy-method="close"><property name="driverClassName"><value>${jdbc.driverClassName}</value></property><property name="url"><value>${jdbc.url}</value></property><property name="username"><value>${jdbc.username}</value></property><property name="password"><value>${jdbc.password}</value></property> <property name="maxActive"> <value>${jdbc.maxActive}</value> </property> <property name="maxIdle"> <value>${jdbc.maxIdle}</value> </property> <property name="maxWait"> <value>${jdbc.maxWait}</value> </property></bean>