最近在运行项目的时候总是报错:Caused by: com.alibaba.druid.pool.GetConnectionTimeoutException: wait millis 5003, active 20, maxActive 20, creating 0,改了配置文件也改了代码,甚至以为是自己的电脑不行。那就只可能是代码问题,终于在苦苦排查下发现了问题,竟然是一个如此低级的错误
报错原因:
public List<T> getList(String sql, Class<T> tClass, Object... parameters) {
Connection connection = JDBCUitlsByDruid.getConnection();
try {
List<T> list = queryRunner.query(connection, sql, new BeanListHandler<>(tClass), parameters);
return list;
} catch (SQLException e) {
throw new RuntimeException(e);
}
}
上面代码在查询完数据库后,没有关闭数据库connection连接,项目运行时多次发出请求,当连接数量达到上限时,则会报错。
(其中数量的上限条件可能是电脑内存资源的上限、或者是配置文件中最高连接数量的上限)
解决办法:手动关闭连接
public List<T> getList(String sql, Class<T> tClass, Object... parameters) {
Connection connection = JDBCUitlsByDruid.getConnection();
try {
List<T> list = queryRunner.query(connection, sql, new BeanListHandler<>(tClass), parameters);
return list;
} catch (SQLException e) {
throw new RuntimeException(e);
} finally {
JDBCUitlsByDruid.close(connection, null, null);
}
}