spring boot (2.2.x) 中默认使用hikariCP作为连接池,配置如下
applicaiton.yml
1 2 3 4 5 6 7 8 9 10 11 12
| spring: datasource: driverClassName: org.postgresql.Driver url: jdbc:postgresql://db-server:5433/mydb username: pgdbo password: sql hikari: maximum-pool-size: 20 minimum-idle: 5 idle-timeout: 10000 connection-timeout: 8000 connection-test-query: select 1
|
如果不配置,默认的超时时间10分钟,minimum-dile是10个
如果我们希望监视当前有多少个activeConnection,可以通过如下方法
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| @Autowired private DataSource dataSource; if (dataSource instanceof HikariDataSource) { HikariDataSource hds = (HikariDataSource) dataSource; if (hds.getHikariPoolMXBean() == null) { try { Connection conn = hds.getConnection(); conn.close(); } catch (SQLException sqlException) { logger.error("cannot get conn", sqlException); } } HikariPoolMXBean pool = hds.getHikariPoolMXBean(); if (pool != null) { Map<String, Object> poolStatus = new HashMap<>(); poolStatus.put("active", pool.getActiveConnections()); poolStatus.put("idle", pool.getIdleConnections()); poolStatus.put("total", pool.getTotalConnections()); poolStatus.put("awaiting", pool.getThreadsAwaitingConnection()); poolStatus.put("maximumPoolSize", hds.getMaximumPoolSize()); poolStatus.put("minimumIdle", hds.getMinimumIdle()); poolStatus.put("idleTimeout", hds.getIdleTimeout()); result.put("dataSourcePool", poolStatus); } }
|
注意第4到第12行那部分,如果连接池一次也没被执行过(获取过连接),那么getHikariPoolMXBean() 会返回null,无法获取信息,需要手工执行一次getConnection