连接池关于主动关闭连接的问题分析
讨论1. 使用连接池后在通过连接池获取连接,进行数据库操作时, 是否需要主动关闭连接
项目中使用了apache dbcp 连接池后, 点击查询,当查询多次后,报如下错误:
?
?
??
maxWait默认为-1L ,一直等待.
maxActive和maxWait 设置需根据项目实际访问情况设置.?
?
2).?minIdle:?
?最小空闲数,即:连接池中保持连接的最小数, 此属性越接近实际访问大小,效率越高. 默认为0,即无连接.
根据本项目实际情况设置为2.(项目为个人开发)
?
3). 关于对于未关闭连接的管理处理的参数:
removeAbandoned: ?是否关闭未关闭的连接, 默认为false, 改为true ,即超过removeAbandonedTimeout的连接,进行强制关闭.
removeAbandonedTimeout:默认为300(单位秒)即5分钟, 根据操作数据时间来判断, 由于本系统访问较小且无复杂操作,设置为30s
logAbandoned: 关闭连接是否记录日志, 默认为false,改为true.
源码如下:
?
public class AbandonedConfig { /** * Whether or not a connection is considered abandoned and eligible * for removal if it has been idle longer than the removeAbandonedTimeout */ private boolean removeAbandoned = false; /** * Timeout in seconds before an abandoned connection can be removed */ private int removeAbandonedTimeout = 300; /** * Determines whether or not to log stack traces for application code * which abandoned a Statement or Connection. */ private boolean logAbandoned = false;?设置此组参数的意义:
程序在获取连接进行数据库操作时 ,当未关闭连接, 设置了此参数,可以强制关闭这些连接.
这样可以减少对数据库连接的占用. 但对于连接保持时间参数timeout值的设置,需要斟酌考虑.
?
总结: 数据库连接池给我们操作数据库带来了方便,通过配置可以关闭未关闭的连接, 但在程序中能根据业务处理完成后,关闭连接,?更合理些.
?
?
?
?