聊聊druid连接池的监控

本文主要研究一下druid连接池的监控

init

com/alibaba/druid/pool/DruidDataSource.java

public void init() throws SQLException {
	//......
	registerMbean();
	//......
}

DruidDataSource的init方法会执行registerMbean

registerMbean

com/alibaba/druid/pool/DruidDataSource.java

    public void registerMbean() {
        if (!mbeanRegistered) {
            AccessController.doPrivileged(new PrivilegedAction<Object>() {
                @Override
                public Object run() {
                    ObjectName objectName = DruidDataSourceStatManager.addDataSource(DruidDataSource.this,
                            DruidDataSource.this.name);

                    DruidDataSource.this.setObjectName(objectName);
                    DruidDataSource.this.mbeanRegistered = true;

                    return null;
                }
            });
        }
    }

registerMbean会执行DruidDataSourceStatManager.addDataSource(DruidDataSource.this, DruidDataSource.this.name)

DruidDataSourceStatManager

com/alibaba/druid/stat/DruidDataSourceStatManager.java

    public static synchronized ObjectName addDataSource(Object dataSource, String name) {
        final Map<Object, ObjectName> instances = getInstances();

        MBeanServer mbeanServer = ManagementFactory.getPlatformMBeanServer();
        synchronized (instances) {
            if (instances.size() == 0) {
                try {
                    ObjectName objectName = new ObjectName(MBEAN_NAME);
                    if (!mbeanServer.isRegistered(objectName)) {
                        mbeanServer.registerMBean(instance, objectName);
                    }
                } catch (JMException ex) {
                    LOG.error("register mbean error", ex);
                }

                DruidStatService.registerMBean();
            }
        }

        ObjectName objectName = null;
        if (name != null) {
            try {
                objectName = new ObjectName("com.alibaba.druid:type=DruidDataSource,id=" + name);
                mbeanServer.registerMBean(dataSource, objectName);
            } catch (Throwable ex) {
                LOG.error("register mbean error", ex);
                objectName = null;
            }
        }

        if (objectName == null) {
            try {
                int id = System.identityHashCode(dataSource);
                objectName = new ObjectName("com.alibaba.druid:type=DruidDataSource,id=" + id);
                mbeanServer.registerMBean(dataSource, objectName);
            } catch (Throwable ex) {
                LOG.error("register mbean error", ex);
                objectName = null;
            }
        }

        instances.put(dataSource, objectName);
        return objectName;
    }

DruidDataSourceStatManager的addDataSource方法通过mbeanServer.registerMBean(dataSource, objectName)将DruidDataSource注册到mbeanServer中,而DruidDataSource则实现了DruidDataSourceMBean接口

DruidDataSourceMBean

public interface DruidDataSourceMBean extends DruidAbstractDataSourceMBean {
    long getResetCount();

    boolean isEnable();

    String getUrl();

    void shrink();

    int removeAbandoned();

    String dump();

    int getWaitThreadCount();

    int getLockQueueLength();

    long getNotEmptyWaitCount();

    int getNotEmptyWaitThreadCount();

    long getNotEmptySignalCount();

    long getNotEmptyWaitMillis();

    long getNotEmptyWaitNanos();

    void resetStat();

    boolean isResetStatEnable();

    void setResetStatEnable(boolean resetStatEnable);

    String getVersion();

    void setPoolPreparedStatements(boolean poolPreparedStatements);

    int getActivePeak();

    int getPoolingPeak();

    Date getActivePeakTime();

    Date getPoolingPeakTime();

    long getErrorCount();

    ObjectName getObjectName();

    void clearStatementCache() throws SQLException;

    long getDiscardCount();

    void setStatLoggerClassName(String className);

    long getTimeBetweenLogStatsMillis();

    void setTimeBetweenLogStatsMillis(long timeBetweenLogStatsMillis);

    void setConnectionProperties(String connectionProperties);

    int fill() throws SQLException;

    int fill(int toCount) throws SQLException;

    boolean isUseGlobalDataSourceStat();
}

DruidDataSourceMBean按jmx规范命名以MBean结尾,它定义了一系列的getter和操作方法,它还继承了DruidAbstractDataSourceMBean

DruidAbstractDataSourceMBean

com/alibaba/druid/pool/DruidAbstractDataSourceMBean.java

public interface DruidAbstractDataSourceMBean {
    int getLoginTimeout();

    String getDbType();

    String getName();

    int getInitialSize();

    String getUsername();

    String getUrl();

    String getDriverClassName();

    long getConnectCount();

    long getCloseCount();

    long getConnectErrorCount();

    int getPoolingCount();

    long getRecycleCount();

    int getActiveCount();

    long getCreateCount();

    long getDestroyCount();

    long getCreateTimespanMillis();

    long getCommitCount();

    long getRollbackCount();

    long getStartTransactionCount();

    int getQueryTimeout();

    int getTransactionQueryTimeout();

    String getValidationQuery();

    int getValidationQueryTimeout();

    int getMaxWaitThreadCount();

    long getTimeBetweenEvictionRunsMillis();

    long getMinEvictableIdleTimeMillis();

    boolean isRemoveAbandoned();

    long getRemoveAbandonedTimeoutMillis();

    List<String> getActiveConnectionStackTrace();

    List<String> getFilterClassNames();

    boolean isTestOnBorrow();

    void setTestOnBorrow(boolean testOnBorrow);

    boolean isTestOnReturn();

    boolean isTestWhileIdle();

    void setTestWhileIdle(boolean testWhileIdle);

    boolean isDefaultAutoCommit();

    Boolean getDefaultReadOnly();

    Integer getDefaultTransactionIsolation();

    String getDefaultCatalog();

    boolean isPoolPreparedStatements();

    boolean isSharePreparedStatements();

    long getMaxWait();

    int getMinIdle();

    int getMaxIdle();

    long getCreateErrorCount();

    int getMaxActive();

    void setMaxActive(int maxActive);

    long getTimeBetweenConnectErrorMillis();

    int getMaxOpenPreparedStatements();

    long getRemoveAbandonedCount();

    boolean isLogAbandoned();

    void setLogAbandoned(boolean logAbandoned);

    long getDupCloseCount();

    boolean isBreakAfterAcquireFailure();

    int getConnectionErrorRetryAttempts();

    int getMaxPoolPreparedStatementPerConnectionSize();

    void setMaxPoolPreparedStatementPerConnectionSize(int maxPoolPreparedStatementPerConnectionSize);

    String getProperties();

    int getRawDriverMinorVersion();

    int getRawDriverMajorVersion();

    Date getCreatedTime();

    String getValidConnectionCheckerClassName();

    long[] getTransactionHistogramValues();

    void setTransactionThresholdMillis(long transactionThresholdMillis);

    long getTransactionThresholdMillis();

    long getPreparedStatementCount();

    long getClosedPreparedStatementCount();

    long getCachedPreparedStatementCount();

    long getCachedPreparedStatementDeleteCount();

    long getCachedPreparedStatementAccessCount();

    long getCachedPreparedStatementMissCount();

    long getCachedPreparedStatementHitCount();

    boolean isUseOracleImplicitCache();

    void setUseOracleImplicitCache(boolean useOracleImplicitCache);

    int getDriverMajorVersion();

    int getDriverMinorVersion();

    String getExceptionSorterClassName();
}

DruidAbstractDataSourceMBean定义了暴露给jmx的一系列方法

getStatDataForMBean

com/alibaba/druid/pool/DruidDataSource.java

    public Map<String, Object> getStatDataForMBean() {
        try {
            Map<String, Object> map = new HashMap<String, Object>();

            // 0 - 4
            map.put("Name", this.getName());
            map.put("URL", this.getUrl());
            map.put("CreateCount", this.getCreateCount());
            map.put("DestroyCount", this.getDestroyCount());
            map.put("ConnectCount", this.getConnectCount());

            // 5 - 9
            map.put("CloseCount", this.getCloseCount());
            map.put("ActiveCount", this.getActiveCount());
            map.put("PoolingCount", this.getPoolingCount());
            map.put("LockQueueLength", this.getLockQueueLength());
            map.put("WaitThreadCount", this.getNotEmptyWaitThreadCount());

            // 10 - 14
            map.put("InitialSize", this.getInitialSize());
            map.put("MaxActive", this.getMaxActive());
            map.put("MinIdle", this.getMinIdle());
            map.put("PoolPreparedStatements", this.isPoolPreparedStatements());
            map.put("TestOnBorrow", this.isTestOnBorrow());

            // 15 - 19
            map.put("TestOnReturn", this.isTestOnReturn());
            map.put("MinEvictableIdleTimeMillis", this.minEvictableIdleTimeMillis);
            map.put("ConnectErrorCount", this.getConnectErrorCount());
            map.put("CreateTimespanMillis", this.getCreateTimespanMillis());
            map.put("DbType", this.dbTypeName);

            // 20 - 24
            map.put("ValidationQuery", this.getValidationQuery());
            map.put("ValidationQueryTimeout", this.getValidationQueryTimeout());
            map.put("DriverClassName", this.getDriverClassName());
            map.put("Username", this.getUsername());
            map.put("RemoveAbandonedCount", this.getRemoveAbandonedCount());

            // 25 - 29
            map.put("NotEmptyWaitCount", this.getNotEmptyWaitCount());
            map.put("NotEmptyWaitNanos", this.getNotEmptyWaitNanos());
            map.put("ErrorCount", this.getErrorCount());
            map.put("ReusePreparedStatementCount", this.getCachedPreparedStatementHitCount());
            map.put("StartTransactionCount", this.getStartTransactionCount());

            // 30 - 34
            map.put("CommitCount", this.getCommitCount());
            map.put("RollbackCount", this.getRollbackCount());
            map.put("LastError", JMXUtils.getErrorCompositeData(this.getLastError()));
            map.put("LastCreateError", JMXUtils.getErrorCompositeData(this.getLastCreateError()));
            map.put("PreparedStatementCacheDeleteCount", this.getCachedPreparedStatementDeleteCount());

            // 35 - 39
            map.put("PreparedStatementCacheAccessCount", this.getCachedPreparedStatementAccessCount());
            map.put("PreparedStatementCacheMissCount", this.getCachedPreparedStatementMissCount());
            map.put("PreparedStatementCacheHitCount", this.getCachedPreparedStatementHitCount());
            map.put("PreparedStatementCacheCurrentCount", this.getCachedPreparedStatementCount());
            map.put("Version", this.getVersion());

            // 40 -
            map.put("LastErrorTime", this.getLastErrorTime());
            map.put("LastCreateErrorTime", this.getLastCreateErrorTime());
            map.put("CreateErrorCount", this.getCreateErrorCount());
            map.put("DiscardCount", this.getDiscardCount());
            map.put("ExecuteQueryCount", this.getExecuteQueryCount());

            map.put("ExecuteUpdateCount", this.getExecuteUpdateCount());

            return map;
        } catch (JMException ex) {
            throw new IllegalStateException("getStatData error", ex);
        }
    }

DruidDataSource的getStatDataForMBean定义了给jmx的所有监控项

DruidDataSourceUtils

com/alibaba/druid/util/DruidDataSourceUtils.java

    public static Map<String, Object> getStatDataForMBean(Object druidDataSource) {
        if (druidDataSource.getClass() == DruidDataSource.class) {
            return ((DruidDataSource) druidDataSource).getStatDataForMBean();
        }

        try {
            Method method = druidDataSource.getClass().getMethod("getStatDataForMBean");
            Object obj = method.invoke(druidDataSource);
            return (Map<String, Object>) obj;
        } catch (Exception e) {
            LOG.error("getStatDataForMBean error", e);
            return null;
        }
    }

DruidDataSourceUtils提供了静态方法用于获取监控项

小结

DruidDataSource的init方法会执行registerMbean,把自身注册到mbeanServer,它实现了DruidDataSourceMBean接口;而DruidDataSourceUtils提供了静态方法用于获取监控项,它使用的是DruidDataSource的getStatDataForMBean方法(貌似没直接给到jmx),可以利用该方法把指标暴露给micrometer,之后就可以利用micrometer的集成能力输出到各个监控平台。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Druid连接池是一个专门用于监控数据库连接和SQL执行情况的工具。它被称为"为监控而生的数据库连接池",具有出色的功能、性能和扩展性,超过了其他常见的数据库连接池,如DBCP、C3P0、BoneCP、Proxool、JBoss DataSource等。 Druid连接池可以通过引入Druid提供的监控工具Druid Monitor来实现监控和统计数据源以及SQL的执行情况。这个工具可以帮助开发人员监测连接池的连接情况、性能指标、执行的SQL语句等信息,以便于进行性能调优和故障排查。通过使用Druid Monitor,开发人员可以方便地获取连接池的运行状态、连接数、活跃连接数、SQL执行情况、执行时间等详细信息,从而更好地了解系统的运行情况,及时发现和解决问题。<span class="em">1</span><span class="em">2</span><span class="em">3</span> #### 引用[.reference_title] - *1* *3* [数据库连接池 ( 五 ) Druid 数据监控](https://blog.csdn.net/yuanchun05/article/details/127174870)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] - *2* [druid连接池监控](https://blog.csdn.net/zguoshuaiiii/article/details/78402883)[target="_blank" data-report-click={"spm":"1018.2226.3001.9630","extra":{"utm_source":"vip_chatgpt_common_search_pc_result","utm_medium":"distribute.pc_search_result.none-task-cask-2~all~insert_cask~default-1-null.142^v93^chatsearchT3_1"}}] [.reference_item style="max-width: 50%"] [ .reference_list ]
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值