com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 60000, active 20, maxActive 20, creating 0

活动的连接数为20, 最大的连接数为20, 活动的连接数与最大连接数相同,连接池用完了,在等待60秒后,没有新连接可用,然后超时了。

stat监控页面显示,活跃连接数很高不释放。CPU超过100%

当程序存在缺陷时,申请的连接忘记关闭,这时候,就存在连接泄漏了。

比如Connection connection = jdbcTemplate.getDataSource().getConnection(); 这样得到的连接spring不会再帮你关闭,你需要手动关闭。

1、properties配置:

#druid recycle Druid的连接回收机制
#超过时间限制是否回收
spring.datasource.druid.removeAbandoned = true
#超时时间;单位为秒。180秒=3分钟
spring.datasource.druid.removeAbandonedTimeout = 180
#关闭abanded连接时输出错误日志
spring.datasource.druid.logAbandoned = true

2、xml配置:

<!-- 超过时间限制是否回收 -->  
<property name="removeAbandoned" value="true" />  
<!-- 超时时间;单位为秒。180秒=3分钟 -->  
<property name="removeAbandonedTimeout" value="180" />  
<!-- 关闭abanded连接时输出错误日志 -->  
<property name="logAbandoned" value="true" />

此配置项会影响性能,只在排查的时候打开,系统运行时最好关闭。 

此项配日志会将连接泄漏位置打印出来,手动关闭泄露位置的连接就行了。

 

以下为错误示例就会造成连接泄漏:

public class Test5 {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	private void test() {
		Connection connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			for (int i = 0; i < 2; i++) {
				connection = jdbcTemplate.getDataSource().getConnection();
				// 第一次使用connection
				ps = connection.prepareStatement("select 1 from dual");
				rs = ps.executeQuery();
				while (rs.next()) {
					System.out.println(rs.getString(1));
				}
				// 连接connection可以一直使用,避免频繁创建connection消耗资源
				// ps、rs记得要关闭
				rs.close();
				ps.close();

				// 第二次使用connection
				ps = connection.prepareStatement("select 1 from dual");
				rs = ps.executeQuery();
				while (rs.next()) {
					System.out.println(rs.getString(1));
				}
				// 连接connection可以一直使用,避免频繁创建connection消耗资源
				// ps、rs记得要关闭
				rs.close();
				ps.close();

				// 第三次使用connection
				ps = connection.prepareStatement("select 1 from dual");
				rs = ps.executeQuery();
				while (rs.next()) {
					System.out.println(rs.getString(1));
				}
				// 连接connection可以一直使用,避免频繁创建connection消耗资源
				// ps、rs记得要关闭
				rs.close();
				ps.close();
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	}
}

 

粗略一看没什么问题,finally最终一定会关闭连接,但是仔细看连接在for循环中打开的,实际打开了2个连接只关闭了一个,最终每调用一次该方法就会泄漏一次连接。将connection = jdbcTemplate.getDataSource().getConnection();放在循环外面就解决了。

错误示例二:

public class Test5 {
	@Autowired
	private JdbcTemplate jdbcTemplate;

	private void test() {
		Connection connection = null;
		PreparedStatement ps = null;
		ResultSet rs = null;
		try {
			connection = jdbcTemplate.getDataSource().getConnection();
			ps = connection.prepareStatement(sql);
			rs = ps.executeQuery();
			while (rs.next()) {
				if (rs.getInt(1) == 1) {                    
					test();// 递归
				}
			}
            rs.close();
            ps.close();
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if (connection != null) {
				try {
					connection.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

	}
}

递归也可能会导致,连接数不够。当递归函数需要递归很多次,只有递归结束才开始关闭连接,这期间活跃连接数陡增,若果这个函数被并发调用更恐怖。正确的做法,将connection作为递归函数的参数传递进去。

// isClosed()即使断开连接也会返回false,只有close()后才返回true。
 // isValid(1)单位秒,连接失效返回false。

if (connection == null || connection.isClosed() || !connection.isValid(1)) {
        connection = jdbcTemplate.getDataSource().getConnection();
 }

一般一个connection可以创建300个preparedstatement同时使用,一个connection最大并行299个preparedstatement,记住preparedstatement用完后要关闭,connection每创建一个preparedstatement就相当于打开一个游标,超过300个就会报connection打开游标超出最大数(ORA-01000: 超出打开游标的最大数)。每个线程的preparedstatement应该是并行运行的。

 

所以体现出来spring管理connection连接的好处,不用去关心连接是否已经手动关闭。当项目中大量使用手动维护connection连接时,成千上万代码就会难免忘记关闭connection造成泄漏。

 

 

 

 

 

Druid配置参考:https://github.com/alibaba/druid/wiki/druiddatasource%E9%85%8D%E7%BD%AE

参数配置及说明

属性 说明 建议值
url 数据库的jdbc连接地址。一般为连接oracle/mysql。示例如下:  
  mysql : jdbc:mysql://ip:port/dbname?option1&option2&…  
  oracle : jdbc:oracle:thin:@ip:port:oracle_sid  
     
username 登录数据库的用户名  
password 登录数据库的用户密码  
initialSize 启动程序时,在连接池中初始化多少个连接 10-50已足够
maxActive 连接池中最多支持多少个活动会话  
maxWait 程序向连接池中请求连接时,超过maxWait的值后,认为本次请求失败,即连接池 100
  没有可用连接,单位毫秒,设置-1时表示无限等待  
minEvictableIdleTimeMillis 池中某个连接的空闲时长达到 N 毫秒后, 连接池在下次检查空闲连接时,将 见说明部分
  回收该连接,要小于防火墙超时设置  
  net.netfilter.nf_conntrack_tcp_timeout_established的设置  
timeBetweenEvictionRunsMillis 检查空闲连接的频率,单位毫秒, 非正整数时表示不进行检查  
keepAlive 程序没有close连接且空闲时长超过 minEvictableIdleTimeMillis,则会执 true
  行validationQuery指定的SQL,以保证该程序连接不会池kill掉,其范围不超  
  过minIdle指定的连接个数。  
minIdle 回收空闲连接时,将保证至少有minIdle个连接. 与initialSize相同
removeAbandoned 要求程序从池中get到连接后, N 秒后必须close,否则druid 会强制回收该 false,当发现程序有未
  连接,不管该连接中是活动还是空闲, 以防止进程不会进行close而霸占连接。 正常close连接时设置为true
removeAbandonedTimeout 设置druid 强制回收连接的时限,当程序从池中get到连接开始算起,超过此 应大于业务运行最长时间
  值后,druid将强制回收该连接,单位秒。  
logAbandoned 当druid强制回收连接后,是否将stack trace 记录到日志中 true
testWhileIdle 当程序请求连接,池在分配连接时,是否先检查该连接是否有效。(高效) true
validationQuery 检查池中的连接是否仍可用的 SQL 语句,drui会连接到数据库执行该SQL, 如果  
  正常返回,则表示连接可用,否则表示连接不可用  
testOnBorrow 程序 申请 连接时,进行连接有效性检查(低效,影响性能) false
testOnReturn 程序 返还 连接时,进行连接有效性检查(低效,影响性能) false
poolPreparedStatements 缓存通过以下两个方法发起的SQL: true
  public PreparedStatement prepareStatement(String sql)  
  public PreparedStatement prepareStatement(String sql,  
  int resultSetType, int resultSetConcurrency)  
maxPoolPrepareStatementPerConnectionSize 每个连接最多缓存多少个SQL 20
filters 这里配置的是插件,常用的插件有: stat,wall,slf4j
  监控统计: filter:stat  
  日志监控: filter:log4j 或者 slf4j  
  防御SQL注入: filter:wall  
connectProperties 连接属性。比如设置一些连接池统计方面的配置。  
  druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000  
  比如设置一些数据库连接属性:  
     
Logo

腾讯云面向开发者汇聚海量精品云计算使用和开发经验,营造开放的云计算技术生态圈。

更多推荐