一、异常现象
com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 60000, active 20, maxActive 20, creating 0

二、异常描述
从异常现象中 com.alibaba.druid.pool.GetConnectionTimeoutException 可以看到错误信息提示是阿里巴巴Druid数据库连接池的数据库获取连接超时异常原因,具体为 active 20,活动的连接数为20, maxActive 20, 最大的连接数为20, 意思很明显,活动的连接数与最大连接数相同,连接用完了,在等待(我写的配置是60000毫秒即60秒)新的连接,却没有新连接可用,然后超时了。
 

三、问题原因 

1、事务没提交

开启了事务,但是没有关闭事务,导致连接池一直被占用

应该提交事务,释放连接池

2.

Connection conn = null;  PreparedStatement preState = null;
ResultSet rs = null; 是成员变量。

以上三项放在调用sql的方法体内,别用成员变量,用完后立即关闭释放连接池资源,springboot2以上项目建议用HikariCP

2、连接没关闭

打开了数据库连接,没有关闭,连接池被占用。

每次链接使用完毕,当即在方法体内关闭链接,举例如下,放到finally内关闭会遇上该问题,原因不明,但现象如此。所以要直接在try内就关闭。


	public boolean updateState(List<Push000Bean> list) {
		
		StringBuilder sb = new StringBuilder();
		Connection conn = JdbcUtil.getConnection();
		
		PreparedStatement preState = null;
		
		try {
			conn.setAutoCommit(false);
			preState = conn.prepareStatement(updateSql);
			for(Push000Bean pb : list) {
				preState.setString(1, pb.getPhoneNo());
				preState.addBatch();
			}
			preState.executeBatch();
			conn.commit();
			preState.close();        //立刻关闭
			conn.close();            //立刻关闭
		} catch (SQLException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		
		
		return false;
	}
	

Connection conn = null;
ResultSet rs = null;

PreparedStatement preState = null;

preState = conn.prepareStatement(insertLogSql);

preState.close();

if (rs != null) {
       rs.close();
 }
  if (conn != null) {
       conn.close();
 }

Logo

旨在为数千万中国开发者提供一个无缝且高效的云端环境,以支持学习、使用和贡献开源项目。

更多推荐