我有一个使用 Tomcat JDBC 连接池的服务器应用程序。
这是我用来创建数据源的代码:
PoolProperties connProperties = new PoolProperties();
connProperties.setUrl(resources.getProperty("db.url"));
connProperties.setDriverClassName(resources.getProperty("db.driver"));
connProperties.setUsername(resources.getProperty("db.user"));
connProperties.setPassword(resources.getProperty("db.password"));
connProperties.setJmxEnabled(true);
connProperties.setTestWhileIdle(false);
connProperties.setValidationQuery("SELECT 1");
connProperties.setTestOnReturn(false);
connProperties.setValidationInterval(30000);
connProperties.setTimeBetweenEvictionRunsMillis(30000);
connProperties.setMaxActive(500);
connProperties.setInitialSize(50);
connProperties.setMaxWait(10000);
connProperties.setRemoveAbandonedTimeout(60);
connProperties.setMinEvictableIdleTimeMillis(60000);
connProperties.setSuspectTimeout(60);
connProperties.setMaxIdle(50);
connProperties.setMinIdle(10);
connProperties.setLogAbandoned(false);
connProperties.setRemoveAbandoned(true);
connProperties.setJdbcInterceptors("org.apache.tomcat.jdbc.pool.interceptor.ConnectionState;"+
"org.apache.tomcat.jdbc.pool.interceptor.StatementFinalizer");
dataSource = new DataSource();
dataSource.setPoolProperties(connProperties);
然后我有一个从池中获取连接的方法
protected Connection getDbConnection() throws Exception
{
dbConn = dataSource.getConnection();
return dbConn;
}
每次我想执行一条语句时,我都会调用以下代码:
protected CallableStatement executeCSqlQuery(String sql) throws Exception
{
CallableStatement cstmt;
ResultSet rs = null;
try {
cstmt = getDbConnection().prepareCall(sql);
cstmt.execute();
} catch (SQLException e) {
throw e;
}
return cstmt;
}
这是调用前面代码的示例:
try {
cstmt = dbConnection.executeCSqlQuery(query);
rs = cstmt.getResultSet();
} catch (Exception e) {
// do smething
} finally {
try {
if (cstmt != null) {
cstmt.close();
}
dbConnection.shutdown();
} catch (Exception e) {
// do something
}
}
public void shutdown() {
if (this.dbConn != null)
this.dbConn.close();
}
我面临的问题是,当我每 X 秒在线程中执行一次调用时,我会时不时地收到异常“语句已关闭”。
我不知道为什么会发生这种情况。我认为这可能是驱动程序错误或数据库连接失败(在不同的服务器中运行)。
我没主意了。我缺少什么?
我应该使用c3p0而是连接池?
我设立了赏金来帮助雷兹尼克,但我最终通过查看他的代码找出了问题所在。
问题是每次从池中获取新连接时
protected Connection getDbConnection() throws Exception
{
dbConn = dataSource.getConnection();
return dbConn;
}
物体dbConn
已更新为新连接。
Example:
T1
调用getDbConnection()
T2
调用getDbConnection()
T1
执行查询,处理resultSet
并打电话shutdown()
public void shutdown() {
if (this.dbConn != null)
this.dbConn.close();
}
Because T2
更新了对象,正在使用的连接T2
将被关闭T1
T2
尝试使用该连接,但该连接已关闭。
这样,不必总是更新连接,只需返回它,然后添加额外的逻辑来关闭从池中获取的连接。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)