添加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
@@ -2,6 +2,7 @@ package com.alibaba.druid.logging;
import java.lang.reflect.Constructor;
@SuppressWarnings("rawtypes")
public class LogFactory {
private static Constructor logConstructor;
@@ -14,6 +15,7 @@ public class LogFactory {
tryImplementation("java.lang.Object", "com.ibatis.common.logging.nologging.NoLoggingImpl");
}
@SuppressWarnings("unchecked")
private static void tryImplementation(String testClassName, String implClassName) {
if (logConstructor == null) {
try {
@@ -39,6 +41,7 @@ public class LogFactory {
* Note that this method is only effective for log classes obtained after calling this method. If you intend to use
* this method you should call it before calling any other iBATIS method.
*/
@SuppressWarnings("unchecked")
public static synchronized void selectLog4JLogging() {
try {
Resources.classForName("org.apache.log4j.Logger");
@@ -54,6 +57,7 @@ public class LogFactory {
* or Log4J is on the classpath. Note that this method is only effective for log classes obtained after calling this
* method. If you intend to use this method you should call it before calling any other iBATIS method.
*/
@SuppressWarnings("unchecked")
public static synchronized void selectJavaLogging() {
try {
Resources.classForName("java.util.logging.Logger");
@@ -1,7 +1,10 @@
package com.alibaba.druid.logging;
import java.io.*;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.Reader;
import java.net.URL;
import java.net.URLConnection;
import java.nio.charset.Charset;
@@ -12,297 +15,291 @@ import java.util.Properties;
*/
public class Resources extends Object {
private static ClassLoader defaultClassLoader;
/**
* Charset to use when calling getResourceAsReader.
* null means use the system default.
*/
private static Charset charset;
private static ClassLoader defaultClassLoader;
private Resources() {
}
/**
* Charset to use when calling getResourceAsReader. null means use the system default.
*/
private static Charset charset;
/**
* Returns the default classloader (may be null).
*
* @return The default classloader
*/
public static ClassLoader getDefaultClassLoader() {
return defaultClassLoader;
}
/**
* Sets the default classloader
*
* @param defaultClassLoader - the new default ClassLoader
*/
public static void setDefaultClassLoader(ClassLoader defaultClassLoader) {
Resources.defaultClassLoader = defaultClassLoader;
}
/**
* Returns the URL of the resource on the classpath
*
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static URL getResourceURL(String resource) throws IOException {
return getResourceURL(getClassLoader(), resource);
}
/**
* Returns the URL of the resource on the classpath
*
* @param loader The classloader used to load the resource
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static URL getResourceURL(ClassLoader loader, String resource) throws IOException {
URL url = null;
if (loader != null) url = loader.getResource(resource);
if (url == null) url = ClassLoader.getSystemResource(resource);
if (url == null) throw new IOException("Could not find resource " + resource);
return url;
}
/**
* Returns a resource on the classpath as a Stream object
*
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static InputStream getResourceAsStream(String resource) throws IOException {
return getResourceAsStream(getClassLoader(), resource);
}
/**
* Returns a resource on the classpath as a Stream object
*
* @param loader The classloader used to load the resource
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
InputStream in = null;
if (loader != null) in = loader.getResourceAsStream(resource);
if (in == null) in = ClassLoader.getSystemResourceAsStream(resource);
if (in == null) throw new IOException("Could not find resource " + resource);
return in;
}
/**
* Returns a resource on the classpath as a Properties object
*
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static Properties getResourceAsProperties(String resource)
throws IOException {
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(propfile);
props.load(in);
in.close();
return props;
}
/**
* Returns a resource on the classpath as a Properties object
*
* @param loader The classloader used to load the resource
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static Properties getResourceAsProperties(ClassLoader loader, String resource)
throws IOException {
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(loader, propfile);
props.load(in);
in.close();
return props;
}
/**
* Returns a resource on the classpath as a Reader object
*
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static Reader getResourceAsReader(String resource) throws IOException {
Reader reader;
if (charset == null) {
reader = new InputStreamReader(getResourceAsStream(resource));
} else {
reader = new InputStreamReader(getResourceAsStream(resource), charset);
private Resources(){
}
return reader;
}
/**
* Returns a resource on the classpath as a Reader object
*
* @param loader The classloader used to load the resource
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {
Reader reader;
if (charset == null) {
reader = new InputStreamReader(getResourceAsStream(loader, resource));
} else {
reader = new InputStreamReader(getResourceAsStream(loader, resource), charset);
/**
* Returns the default classloader (may be null).
*
* @return The default classloader
*/
public static ClassLoader getDefaultClassLoader() {
return defaultClassLoader;
}
return reader;
}
/**
* Returns a resource on the classpath as a File object
*
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static File getResourceAsFile(String resource) throws IOException {
return new File(getResourceURL(resource).getFile());
}
/**
* Returns a resource on the classpath as a File object
*
* @param loader - the classloader used to load the resource
* @param resource - the resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException {
return new File(getResourceURL(loader, resource).getFile());
}
/**
* Gets a URL as an input stream
*
* @param urlString - the URL to get
* @return An input stream with the data from the URL
* @throws IOException If the resource cannot be found or read
*/
public static InputStream getUrlAsStream(String urlString) throws IOException {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
return conn.getInputStream();
}
/**
* Gets a URL as a Reader
*
* @param urlString - the URL to get
* @return A Reader with the data from the URL
* @throws IOException If the resource cannot be found or read
*/
public static Reader getUrlAsReader(String urlString) throws IOException {
return new InputStreamReader(getUrlAsStream(urlString));
}
/**
* Gets a URL as a Properties object
*
* @param urlString - the URL to get
* @return A Properties object with the data from the URL
* @throws IOException If the resource cannot be found or read
*/
public static Properties getUrlAsProperties(String urlString) throws IOException {
Properties props = new Properties();
InputStream in = null;
String propfile = urlString;
in = getUrlAsStream(propfile);
props.load(in);
in.close();
return props;
}
/**
* Loads a class
*
* @param className - the class to load
* @return The loaded class
* @throws ClassNotFoundException If the class cannot be found (duh!)
*/
public static Class classForName(String className) throws ClassNotFoundException {
Class clazz = null;
try {
clazz = getClassLoader().loadClass(className);
} catch (Exception e) {
// Ignore. Failsafe below.
/**
* Sets the default classloader
*
* @param defaultClassLoader - the new default ClassLoader
*/
public static void setDefaultClassLoader(ClassLoader defaultClassLoader) {
Resources.defaultClassLoader = defaultClassLoader;
}
if (clazz == null) {
clazz = Class.forName(className);
/**
* Returns the URL of the resource on the classpath
*
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static URL getResourceURL(String resource) throws IOException {
return getResourceURL(getClassLoader(), resource);
}
return clazz;
}
/**
* Creates an instance of a class
*
* @param className - the class to create
* @return An instance of the class
* @throws ClassNotFoundException If the class cannot be found (duh!)
* @throws InstantiationException If the class cannot be instantiaed
* @throws IllegalAccessException If the class is not public, or other access problems arise
*/
public static Object instantiate(String className)
throws ClassNotFoundException, InstantiationException, IllegalAccessException {
return instantiate(classForName(className));
}
/**
* Creates an instance of a class
*
* @param clazz - the class to create
* @return An instance of the class
* @throws InstantiationException If the class cannot be instantiaed
* @throws IllegalAccessException If the class is not public, or other access problems arise
*/
public static Object instantiate(Class clazz)
throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
private static ClassLoader getClassLoader() {
if (defaultClassLoader != null) {
return defaultClassLoader;
} else {
return Thread.currentThread().getContextClassLoader();
/**
* Returns the URL of the resource on the classpath
*
* @param loader The classloader used to load the resource
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static URL getResourceURL(ClassLoader loader, String resource) throws IOException {
URL url = null;
if (loader != null) url = loader.getResource(resource);
if (url == null) url = ClassLoader.getSystemResource(resource);
if (url == null) throw new IOException("Could not find resource " + resource);
return url;
}
}
public static Charset getCharset() {
return charset;
}
/**
* Returns a resource on the classpath as a Stream object
*
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static InputStream getResourceAsStream(String resource) throws IOException {
return getResourceAsStream(getClassLoader(), resource);
}
/**
* Use this method to set the Charset to be used when
* calling the getResourceAsReader methods. This will
* allow iBATIS to function properly when the system default
* encoding doesn't deal well with unicode (IBATIS-340, IBATIS-349)
*
* @param charset
*/
public static void setCharset(Charset charset) {
Resources.charset = charset;
}
/**
* Returns a resource on the classpath as a Stream object
*
* @param loader The classloader used to load the resource
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static InputStream getResourceAsStream(ClassLoader loader, String resource) throws IOException {
InputStream in = null;
if (loader != null) in = loader.getResourceAsStream(resource);
if (in == null) in = ClassLoader.getSystemResourceAsStream(resource);
if (in == null) throw new IOException("Could not find resource " + resource);
return in;
}
/**
* Returns a resource on the classpath as a Properties object
*
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static Properties getResourceAsProperties(String resource) throws IOException {
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(propfile);
props.load(in);
in.close();
return props;
}
/**
* Returns a resource on the classpath as a Properties object
*
* @param loader The classloader used to load the resource
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static Properties getResourceAsProperties(ClassLoader loader, String resource) throws IOException {
Properties props = new Properties();
InputStream in = null;
String propfile = resource;
in = getResourceAsStream(loader, propfile);
props.load(in);
in.close();
return props;
}
/**
* Returns a resource on the classpath as a Reader object
*
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static Reader getResourceAsReader(String resource) throws IOException {
Reader reader;
if (charset == null) {
reader = new InputStreamReader(getResourceAsStream(resource));
} else {
reader = new InputStreamReader(getResourceAsStream(resource), charset);
}
return reader;
}
/**
* Returns a resource on the classpath as a Reader object
*
* @param loader The classloader used to load the resource
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static Reader getResourceAsReader(ClassLoader loader, String resource) throws IOException {
Reader reader;
if (charset == null) {
reader = new InputStreamReader(getResourceAsStream(loader, resource));
} else {
reader = new InputStreamReader(getResourceAsStream(loader, resource), charset);
}
return reader;
}
/**
* Returns a resource on the classpath as a File object
*
* @param resource The resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static File getResourceAsFile(String resource) throws IOException {
return new File(getResourceURL(resource).getFile());
}
/**
* Returns a resource on the classpath as a File object
*
* @param loader - the classloader used to load the resource
* @param resource - the resource to find
* @return The resource
* @throws IOException If the resource cannot be found or read
*/
public static File getResourceAsFile(ClassLoader loader, String resource) throws IOException {
return new File(getResourceURL(loader, resource).getFile());
}
/**
* Gets a URL as an input stream
*
* @param urlString - the URL to get
* @return An input stream with the data from the URL
* @throws IOException If the resource cannot be found or read
*/
public static InputStream getUrlAsStream(String urlString) throws IOException {
URL url = new URL(urlString);
URLConnection conn = url.openConnection();
return conn.getInputStream();
}
/**
* Gets a URL as a Reader
*
* @param urlString - the URL to get
* @return A Reader with the data from the URL
* @throws IOException If the resource cannot be found or read
*/
public static Reader getUrlAsReader(String urlString) throws IOException {
return new InputStreamReader(getUrlAsStream(urlString));
}
/**
* Gets a URL as a Properties object
*
* @param urlString - the URL to get
* @return A Properties object with the data from the URL
* @throws IOException If the resource cannot be found or read
*/
public static Properties getUrlAsProperties(String urlString) throws IOException {
Properties props = new Properties();
InputStream in = null;
String propfile = urlString;
in = getUrlAsStream(propfile);
props.load(in);
in.close();
return props;
}
/**
* Loads a class
*
* @param className - the class to load
* @return The loaded class
* @throws ClassNotFoundException If the class cannot be found (duh!)
*/
public static Class<?> classForName(String className) throws ClassNotFoundException {
Class<?> clazz = null;
try {
clazz = getClassLoader().loadClass(className);
} catch (Exception e) {
// Ignore. Failsafe below.
}
if (clazz == null) {
clazz = Class.forName(className);
}
return clazz;
}
/**
* Creates an instance of a class
*
* @param className - the class to create
* @return An instance of the class
* @throws ClassNotFoundException If the class cannot be found (duh!)
* @throws InstantiationException If the class cannot be instantiaed
* @throws IllegalAccessException If the class is not public, or other access problems arise
*/
public static Object instantiate(String className) throws ClassNotFoundException, InstantiationException,
IllegalAccessException {
return instantiate(classForName(className));
}
/**
* Creates an instance of a class
*
* @param clazz - the class to create
* @return An instance of the class
* @throws InstantiationException If the class cannot be instantiaed
* @throws IllegalAccessException If the class is not public, or other access problems arise
*/
public static Object instantiate(Class<?> clazz) throws InstantiationException, IllegalAccessException {
return clazz.newInstance();
}
private static ClassLoader getClassLoader() {
if (defaultClassLoader != null) {
return defaultClassLoader;
} else {
return Thread.currentThread().getContextClassLoader();
}
}
public static Charset getCharset() {
return charset;
}
/**
* Use this method to set the Charset to be used when calling the getResourceAsReader methods. This will allow
* iBATIS to function properly when the system default encoding doesn't deal well with unicode (IBATIS-340,
* IBATIS-349)
*
* @param charset
*/
public static void setCharset(Charset charset) {
Resources.charset = charset;
}
}
@@ -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;
}
}