添加ConnectionChecker

git-svn-id: http://code.alibabatech.com/svn/druid/trunk@293 b9813039-fb51-4c41-a8b9-e21c2acb5095
This commit is contained in:
wenshao
2011-06-29 04:37:11 +00:00
parent 3c07ac1224
commit d71767db94
8 changed files with 428 additions and 415 deletions
@@ -46,20 +46,20 @@ import com.alibaba.druid.util.DruidLoaderUtils;
*/
public abstract class DruidAbstractDataSource implements DruidAbstractDataSourceMBean, DataSource, DataSourceProxy, Serializable {
private static final long serialVersionUID = 1L;
private static final long serialVersionUID = 1L;
public final static int DEFAULT_INITIAL_SIZE = 0;
public final static int DEFAULT_MAX_ACTIVE_SIZE = 8;
public final static int DEFAULT_MAX_IDLE = 8;
public final static int DEFAULT_MIN_IDLE = 0;
public final static int DEFAULT_MAX_WAIT = -1;
public final static String DEFAULT_VALIDATION_QUERY = null; //
public final static boolean DEFAULT_TEST_ON_BORROW = true;
public final static boolean DEFAULT_TEST_ON_RETURN = false;
public final static boolean DEFAULT_WHILE_IDLE = false;
public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = -1L;
public static final long DEFAULT_TIME_BETWEEN_CONNECT_ERROR_MILLIS = 30 * 1000;
public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 1;
public final static int DEFAULT_INITIAL_SIZE = 0;
public final static int DEFAULT_MAX_ACTIVE_SIZE = 8;
public final static int DEFAULT_MAX_IDLE = 8;
public final static int DEFAULT_MIN_IDLE = 0;
public final static int DEFAULT_MAX_WAIT = -1;
public final static String DEFAULT_VALIDATION_QUERY = null; //
public final static boolean DEFAULT_TEST_ON_BORROW = true;
public final static boolean DEFAULT_TEST_ON_RETURN = false;
public final static boolean DEFAULT_WHILE_IDLE = false;
public static final long DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS = -1L;
public static final long DEFAULT_TIME_BETWEEN_CONNECT_ERROR_MILLIS = 30 * 1000;
public static final int DEFAULT_NUM_TESTS_PER_EVICTION_RUN = 1;
/**
* The default value for {@link #getMinEvictableIdleTimeMillis}.
@@ -67,76 +67,86 @@ public abstract class DruidAbstractDataSource implements DruidAbstractDataSource
* @see #getMinEvictableIdleTimeMillis
* @see #setMinEvictableIdleTimeMillis
*/
public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS = 1000L * 60L * 30L;
public static final long DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS = 1000L * 60L * 30L;
protected boolean defaultAutoCommit = false;
protected Boolean defaultReadOnly;
protected Integer defaultTransactionIsolation;
protected String defaultCatalog = null;
protected boolean defaultAutoCommit = false;
protected Boolean defaultReadOnly;
protected Integer defaultTransactionIsolation;
protected String defaultCatalog = null;
protected String name;
protected String name;
protected String username;
protected String password;
protected String jdbcUrl;
protected String driverClass;
protected Properties connectionProperties = new Properties();
protected String username;
protected String password;
protected String jdbcUrl;
protected String driverClass;
protected Properties connectionProperties = new Properties();
protected PasswordCallback passwordCallback;
protected NameCallback userCallback;
protected PasswordCallback passwordCallback;
protected NameCallback userCallback;
protected ConnectionFactory connectionFactory;
protected ConnectionFactory connectionFactory;
protected int initialSize = DEFAULT_INITIAL_SIZE;
protected int maxActive = DEFAULT_MAX_ACTIVE_SIZE;
protected int minIdle = DEFAULT_MIN_IDLE;
protected int maxIdle = DEFAULT_MAX_IDLE;
protected long maxWait = DEFAULT_MAX_WAIT;
protected int initialSize = DEFAULT_INITIAL_SIZE;
protected int maxActive = DEFAULT_MAX_ACTIVE_SIZE;
protected int minIdle = DEFAULT_MIN_IDLE;
protected int maxIdle = DEFAULT_MAX_IDLE;
protected long maxWait = DEFAULT_MAX_WAIT;
protected String validationQuery = DEFAULT_VALIDATION_QUERY;
protected int validationQueryTimeout = -1;
private boolean testOnBorrow = DEFAULT_TEST_ON_BORROW;
private boolean testOnReturn = DEFAULT_TEST_ON_RETURN;
private boolean testWhileIdle = DEFAULT_WHILE_IDLE;
protected boolean poolPreparedStatements = false;
protected String validationQuery = DEFAULT_VALIDATION_QUERY;
protected int validationQueryTimeout = -1;
private boolean testOnBorrow = DEFAULT_TEST_ON_BORROW;
private boolean testOnReturn = DEFAULT_TEST_ON_RETURN;
private boolean testWhileIdle = DEFAULT_WHILE_IDLE;
protected boolean poolPreparedStatements = false;
protected boolean inited = false;
protected boolean inited = false;
protected PrintWriter logWriter = new PrintWriter(System.out);
protected PrintWriter logWriter = new PrintWriter(System.out);
protected List<Filter> filters = new ArrayList<Filter>();
protected List<Filter> filters = new ArrayList<Filter>();
protected Driver driver;
protected Driver driver;
protected int queryTimeout;
protected int queryTimeout;
protected long createErrorCount;
protected long createErrorCount;
protected long createTimespan;
protected long createTimespan;
protected int maxWaitThreadCount = -1;
protected int maxWaitThreadCount = -1;
protected boolean accessToUnderlyingConnectionAllowed = true;
protected boolean accessToUnderlyingConnectionAllowed = true;
protected long timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
protected long timeBetweenEvictionRunsMillis = DEFAULT_TIME_BETWEEN_EVICTION_RUNS_MILLIS;
protected int numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
protected int numTestsPerEvictionRun = DEFAULT_NUM_TESTS_PER_EVICTION_RUN;
protected long minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
protected long minEvictableIdleTimeMillis = DEFAULT_MIN_EVICTABLE_IDLE_TIME_MILLIS;
protected boolean removeAbandoned;
protected boolean removeAbandoned;
protected int removeAbandonedTimeout;
protected int removeAbandonedTimeout;
protected boolean logAbandoned;
protected boolean logAbandoned;
protected int maxOpenPreparedStatements = -1;
protected int maxOpenPreparedStatements = -1;
protected List<String> connectionInitSqls;
protected List<String> connectionInitSqls;
protected String dbType;
protected String dbType;
protected long timeBetweenConnectErrorMillis = DEFAULT_TIME_BETWEEN_CONNECT_ERROR_MILLIS;
protected long timeBetweenConnectErrorMillis = DEFAULT_TIME_BETWEEN_CONNECT_ERROR_MILLIS;
private ValidConnectionChecker validConnectionChecker = null;
public ValidConnectionChecker getValidConnectionChecker() {
return validConnectionChecker;
}
public void setValidConnectionChecker(ValidConnectionChecker validConnectionChecker) {
this.validConnectionChecker = validConnectionChecker;
}
public String getDbType() {
return dbType;
@@ -645,6 +655,7 @@ public abstract class DruidAbstractDataSource implements DruidAbstractDataSource
if (conn.isClosed()) {
throw new SQLException("validateConnection: connection closed");
}
if (null != query) {
Statement stmt = null;
ResultSet rset = null;
@@ -678,36 +689,43 @@ public abstract class DruidAbstractDataSource implements DruidAbstractDataSource
protected boolean testConnection(Connection conn) {
try {
if (validConnectionChecker != null) {
return validConnectionChecker.isValidConnection(conn);
}
String query = getValidationQuery();
if (conn.isClosed()) {
return false;
}
if (null != query) {
Statement stmt = null;
ResultSet rset = null;
try {
stmt = conn.createStatement();
if (getValidationQueryTimeout() > 0) {
stmt.setQueryTimeout(getValidationQueryTimeout());
if (null == query) {
return true;
}
Statement stmt = null;
ResultSet rset = null;
try {
stmt = conn.createStatement();
if (getValidationQueryTimeout() > 0) {
stmt.setQueryTimeout(getValidationQueryTimeout());
}
rset = stmt.executeQuery(query);
if (!rset.next()) {
return false;
}
} finally {
if (rset != null) {
try {
rset.close();
} catch (Exception t) {
// ignored
}
rset = stmt.executeQuery(query);
if (!rset.next()) {
return false;
}
} finally {
if (rset != null) {
try {
rset.close();
} catch (Exception t) {
// ignored
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception t) {
// ignored
}
}
if (stmt != null) {
try {
stmt.close();
} catch (Exception t) {
// ignored
}
}
}
@@ -747,14 +765,13 @@ public abstract class DruidAbstractDataSource implements DruidAbstractDataSource
public long createResultSetId() {
return resultSetIdSeed.getAndIncrement();
}
void initStatement(Statement stmt) throws SQLException {
if (queryTimeout > 0) {
stmt.setQueryTimeout(queryTimeout);
}
}
protected abstract void recycle(PoolableConnection pooledConnection) throws SQLException;
abstract void incrementCreateCount();
@@ -71,7 +71,10 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
private final IdentityHashMap<PoolableConnection, ActiveConnectionTraceInfo> activeConnections = new IdentityHashMap<PoolableConnection, ActiveConnectionTraceInfo>();
private final CountDownLatch initedLatch = new CountDownLatch(2);
private final CountDownLatch initedLatch = new CountDownLatch(
2);
public DruidDataSource(){
}
@@ -188,7 +191,8 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
final int maxWaitThreadCount = getMaxWaitThreadCount();
if (maxWaitThreadCount > 0) {
if (lock.getQueueLength() > maxWaitThreadCount) {
throw new SQLException("maxWaitThreadCount " + maxWaitThreadCount + ", current wait Thread count " + lock.getQueueLength());
throw new SQLException("maxWaitThreadCount " + maxWaitThreadCount + ", current wait Thread count "
+ lock.getQueueLength());
}
}
@@ -236,7 +240,9 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
if (activeConnectionTraceEnable) {
StackTraceElement[] stackTrace = Thread.currentThread().getStackTrace();
activeConnections.put(poolalbeConnection, new ActiveConnectionTraceInfo(poolalbeConnection, System.currentTimeMillis(), stackTrace));
activeConnections.put(poolalbeConnection,
new ActiveConnectionTraceInfo(poolalbeConnection, System.currentTimeMillis(),
stackTrace));
}
} catch (InterruptedException e) {
connectErrorCount++;
@@ -441,10 +447,10 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
nanos = estimate;
continue;
}
return null;
}
break;
}
}
@@ -524,7 +530,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
Connection connection = connectionFactory.createConnection();
ConnectionHolder poolableConnection = new ConnectionHolder(DruidDataSource.this, connection);
connections[count++] = poolableConnection;
errorCount = 0; // reset errorCount
notEmpty.signal();
@@ -533,7 +539,7 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
break;
} catch (SQLException e) {
printStackTrace(e);
errorCount++;
if (errorCount > MAX_ERRRO_TRY && timeBetweenConnectErrorMillis > 0) {
@@ -621,7 +627,6 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
return null;
}
/** Instance key */
protected String instanceKey = null;
@@ -682,6 +687,5 @@ public class DruidDataSource extends DruidAbstractDataSource implements DruidDat
}
return names;
}
}
@@ -4,5 +4,5 @@ import java.sql.Connection;
import java.sql.SQLException;
public interface ValidConnectionChecker {
SQLException isValidConnection(Connection c);
boolean isValidConnection(Connection c);
}
@@ -45,23 +45,19 @@ public class MSSQLValidConnectionChecker implements ValidConnectionChecker, Seri
/** The serialVersionUID */
private static final long serialVersionUID = 3995516551833725723L;
public SQLException isValidConnection(final Connection c) {
SQLException sqe = null;
public boolean isValidConnection(final Connection c) {
Statement stmt = null;
try {
stmt = c.createStatement();
stmt.execute(QUERY);
}
catch (SQLException e) {
return true;
} catch (SQLException e) {
LOG.warn("warning: connection validation failed for current managed connection.");
sqe = e;
return false;
} finally {
JdbcUtils.close(stmt);
}
return sqe;
}
}
@@ -36,41 +36,35 @@ public class MySQLValidConnectionChecker implements ValidConnectionChecker, Seri
}
}
public SQLException isValidConnection(Connection c) {
public boolean isValidConnection(Connection c) {
// if there is a ping method then use it, otherwise just use a 'SELECT 1' statement
if (driverHasPingMethod) {
try {
ping.invoke(c, params);
return true;
} catch (Exception e) {
if (e instanceof SQLException) {
return (SQLException) e;
} else {
LOG.warn("Unexpected error in ping", e);
return new SQLException("ping failed: " + e.toString());
}
}
} else {
Statement stmt = null;
ResultSet rs = null;
try {
stmt = c.createStatement();
rs = stmt.executeQuery("SELECT 1");
} catch (Exception e) {
if (e instanceof SQLException) {
return (SQLException) e;
} else {
LOG.warn("Unexpected error in ping (SELECT 1)", e);
return new SQLException("ping (SELECT 1) failed: " + e.toString());
}
} finally {
JdbcUtils.close(rs);
JdbcUtils.close(stmt);
LOG.warn("Unexpected error in ping", e);
return false;
}
}
return null;
Statement stmt = null;
ResultSet rs = null;
try {
stmt = c.createStatement();
rs = stmt.executeQuery("SELECT 1");
return true;
} catch (SQLException e) {
return false;
} catch (Exception e) {
LOG.warn("Unexpected error in ping", e);
return false;
} finally {
JdbcUtils.close(rs);
JdbcUtils.close(stmt);
}
}
}
@@ -24,7 +24,6 @@ package com.alibaba.druid.pool.vendor;
import java.io.Serializable;
import java.lang.reflect.Method;
import java.sql.Connection;
import java.sql.SQLException;
import com.alibaba.druid.logging.Log;
import com.alibaba.druid.logging.LogFactory;
@@ -51,17 +50,19 @@ public class OracleValidConnectionChecker implements ValidConnectionChecker, Ser
}
}
public SQLException isValidConnection(Connection c) {
public boolean isValidConnection(Connection c) {
try {
Integer status = (Integer) ping.invoke(c, params);
// Error
if (status.intValue() < 0) return new SQLException("pingDatabase failed status=" + status);
if (status.intValue() < 0) {
return false;
}
} catch (Exception e) {
LOG.warn("Unexpected error in pingDatabase", e);
}
// OK
return null;
return true;
}
}