Yesterday I was facing one production issue where somehow at some time the connection to a database which is located at another server will be reset. I was getting java.lang.SqlException(io exception: connection resrt). I have reused a method that will reconnect to the database. I hope it works in the next deployment and i believe it should work. Code snippet as below:
public Connection getDBConnection(String dbName) throws OracleConnException, Exception { if (logger.isInfoEnabled()) { logger.info("getDBConnection(String) - String dbName=" + dbName); //$NON-NLS-1$ }
Connection cachedConnection = null; if (ocDataSource == null) { ocDataSource = new HashMap(); this.printSQL("new HashMap"); }
OracleDataSource ds = (OracleDataSource) ocDataSource.get(dbName);
if(ds == null){ this.printSQL("creatingNewOracleDS"); ds = createNewOracleDS(dbName); this.printSQL("createdNewOracleDS"); ocDataSource.put(dbName.trim(), ds); }
int i = 0; int retry = KenanAdaptorProperties.getORACLE_RETRY_NUM();
for(i = 0; i < retry; i++){ try { this.printSQL("ds.getConnection() " + ds.getPortNumber());
cachedConnection = ds.getConnection(); this.printSQL("error in connection? ");
if(!isConnectionAlive(cachedConnection)){ this.printSQL("connection is not alive???"); try { ds.close(); } catch(Exception e){ //log.debug("Can't close DataSource object!"); } ds = null;
ocDataSource.remove(dbName);
ds = createNewOracleDS(dbName); ocDataSource.put(dbName, ds); } else { break; }
} catch (SQLException se){ logger.error("getDBConnection(String)", se); //$NON-NLS-1$ } catch (Exception e){ this.printSQL("Exception:\r\n" + Util.getStackTraceForLog(e)); }
// sleep for a specific amount of time! //make it configurable try { Thread.sleep(KenanAdaptorProperties.getORACLE_RETRY_SLEEP_TIME()); } catch (InterruptedException e) { // log.debug("Interrupted Exception:\r\n" + Util.getStackTraceForLog(e)); }
}
if(i == retry){ throw new OracleConnException("Connection is not established. Failed after " + retry + " retries."); }
return cachedConnection; }
|
No comments:
Post a Comment