A high-performance JDBC connection pool and database monitoring library with SQL parsing and security features
—
Complete guide to configuring Druid DataSource for JDBC connection pooling with comprehensive parameter control and optimization options.
// Constructor-based creation
DruidDataSource dataSource = new DruidDataSource();
DruidDataSource dataSource = new DruidDataSource(boolean fairLock);
// Factory-based creation
DataSource dataSource = DruidDataSourceFactory.createDataSource(Properties properties);
DataSource dataSource = DruidDataSourceFactory.createDataSource(Map<String, Object> properties);// Essential connection configuration
void setUrl(String jdbcUrl);
void setUsername(String username);
void setPassword(String password);
void setDriverClassName(String driverClass);
void setDriverClassLoader(ClassLoader classLoader);
void setConnectProperties(Properties properties);
void setConnectionProperties(String connectionProperties);
// Connection behavior
void setDefaultAutoCommit(Boolean autoCommit);
void setDefaultReadOnly(Boolean readOnly);
void setDefaultTransactionIsolation(Integer isolationLevel);
void setDefaultCatalog(String catalog);// Pool sizing parameters
void setInitialSize(int initialSize); // Default: 0
void setMaxActive(int maxActive); // Default: 8
void setMinIdle(int minIdle); // Default: 0
void setMaxIdle(int maxIdle); // Deprecated
// Connection acquisition
void setMaxWait(long maxWaitMillis); // Default: -1 (no timeout)
void setMaxWaitThreadCount(int maxWaitThreadCount);
void setNotFullTimeoutRetryCount(int count);// Eviction timing controls
void setTimeBetweenEvictionRunsMillis(long millis); // Default: 60000ms
void setMinEvictableIdleTimeMillis(long millis); // Default: 30min
void setMaxEvictableIdleTimeMillis(long millis); // Default: 7h
// Connection lifecycle
void setKeepAliveBetweenTimeMillis(long millis);
void setPhyTimeoutMillis(long millis);
void setPhyMaxUseCount(long count);
// Timeout configuration
void setConnectTimeout(int milliseconds); // Default: 10000ms
void setSocketTimeout(int milliseconds); // Default: 10000ms
void setQueryTimeout(int seconds);
void setTransactionQueryTimeout(int seconds);// Validation query setup
void setValidationQuery(String query);
void setValidationQueryTimeout(int timeout);
void setValidConnectionChecker(ValidConnectionChecker checker);
void setValidConnectionCheckerClassName(String className);
// Test timing configuration
void setTestOnBorrow(boolean test); // Default: false
void setTestOnReturn(boolean test); // Default: false
void setTestWhileIdle(boolean test); // Default: true// Example validation configuration
dataSource.setValidationQuery("SELECT 1");
dataSource.setValidationQueryTimeout(5);
dataSource.setTestWhileIdle(true);
dataSource.setTestOnBorrow(false);
dataSource.setTimeBetweenEvictionRunsMillis(60000);// PreparedStatement caching
void setPoolPreparedStatements(boolean pool);
void setMaxPoolPreparedStatementPerConnectionSize(int size); // Default: 10
void setSharePreparedStatements(boolean share);// Abandoned connection detection
void setRemoveAbandoned(boolean remove);
void setRemoveAbandonedTimeout(int timeout); // Seconds
void setRemoveAbandonedTimeoutMillis(long millis);
void setLogAbandoned(boolean log);// Error recovery configuration
void setConnectionErrorRetryAttempts(int attempts); // Default: 1
void setBreakAfterAcquireFailure(boolean breakAfter);
void setTimeBetweenConnectErrorMillis(long millis); // Default: 500ms
void setExceptionSorter(ExceptionSorter sorter);
void setExceptionSorterClassName(String className);// Performance tuning
void setAsyncInit(boolean async);
void setKeepAlive(boolean keepAlive);
void setUseUnfairLock(boolean unfair); // Default: true
void setFailFast(boolean failFast);
void setKillWhenSocketReadTimeout(boolean kill);
// Filter configuration
void setFilters(String filters); // e.g., "stat,wall,log4j"
void setProxyFilters(List<Filter> filters);
void setClearFiltersEnable(boolean enable);// Connection initialization
void setConnectionInitSqls(Collection<String> sqls);
void setInitVariants(boolean init);
void setInitGlobalVariants(boolean init);
void setInitExceptionThrow(boolean throwException);// Lifecycle management
void init() throws SQLException;
void close();
void restart() throws SQLException;
void restart(Properties properties) throws SQLException;
// Runtime management
boolean isClosed();
boolean isEnable();
void setEnable(boolean enable);
int fill() throws SQLException;
int fill(int toCount) throws SQLException;
void shrink();
void shrink(boolean checkTime);
void shrink(boolean checkTime, boolean keepAlive);
void clearStatementCache() throws SQLException;
int removeAbandoned();
boolean isFull();// Standard connection methods
Connection getConnection() throws SQLException;
Connection getConnection(String username, String password) throws SQLException;
DruidPooledConnection getConnection(long maxWaitMillis) throws SQLException;
// Direct and advanced connection methods
DruidPooledConnection getConnectionDirect(long maxWaitMillis) throws SQLException;
DruidPooledConnection tryGetConnection() throws SQLException;
boolean discardConnection(Connection conn);
// PooledConnection interface methods
PooledConnection getPooledConnection() throws SQLException;
PooledConnection getPooledConnection(String user, String password) throws SQLException;// Configuration from properties
void configFromProperties(Properties properties);
// Filter management
void addFilters(String filters) throws SQLException;
void clearFilters();
List<Filter> getProxyFilters();
List<String> getFilterClassNames();
// MBean management
void registerMbean();
void unregisterMbean();
boolean isMbeanRegistered();
ObjectName getObjectName();
void setObjectName(ObjectName objectName);// Properties-based configuration example
Properties config = new Properties();
config.setProperty("url", "jdbc:mysql://localhost:3306/test");
config.setProperty("username", "root");
config.setProperty("password", "password");
config.setProperty("driverClassName", "com.mysql.cj.jdbc.Driver");
// Pool configuration
config.setProperty("initialSize", "5");
config.setProperty("maxActive", "20");
config.setProperty("minIdle", "5");
config.setProperty("maxWait", "60000");
// Validation
config.setProperty("validationQuery", "SELECT 1");
config.setProperty("testWhileIdle", "true");
config.setProperty("testOnBorrow", "false");
// Timing
config.setProperty("timeBetweenEvictionRunsMillis", "60000");
config.setProperty("minEvictableIdleTimeMillis", "300000");
// Features
config.setProperty("poolPreparedStatements", "true");
config.setProperty("maxPoolPreparedStatementPerConnectionSize", "20");
config.setProperty("filters", "stat,wall,slf4j");
// Create DataSource
DataSource dataSource = DruidDataSourceFactory.createDataSource(config);// Statistics configuration
void setTimeBetweenLogStatsMillis(long millis);
void setStatLogger(DruidDataSourceStatLogger logger);
void setStatLoggerClassName(String className);
void setResetStatEnable(boolean enable);
void setTransactionThresholdMillis(long millis);
// Monitoring setup
void setName(String name); // DataSource name for monitoring
void setDbType(String dbType); // Database type hint
void setUseGlobalDataSourceStat(boolean global);// Connection pool statistics
long getCreateCount();
long getDestroyCount();
long getConnectCount();
long getCloseCount();
long getConnectErrorCount();
long getErrorCount();
long getRecycleCount();
long getRecycleErrorCount();
long getDiscardCount();
// Pool state statistics
int getPoolingCount();
int getActiveCount();
int getActivePeak();
Date getActivePeakTime();
int getPoolingPeak();
Date getPoolingPeakTime();
// Wait thread statistics
int getWaitThreadCount();
long getNotEmptyWaitCount();
int getNotEmptyWaitThreadCount();
int getNotEmptyWaitThreadPeak();
long getNotEmptySignalCount();
long getNotEmptyWaitMillis();
long getNotEmptyWaitNanos();
// Execution statistics
long getExecuteCount();
long getExecuteUpdateCount();
long getExecuteQueryCount();
long getExecuteBatchCount();
long getCommitCount();
long getRollbackCount();
long getStartTransactionCount();
// PreparedStatement statistics
long getCachedPreparedStatementHitCount();
long getCachedPreparedStatementMissCount();
long getCachedPreparedStatementAccessCount();
long getCachedPreparedStatementDeleteCount();
long getCachedPreparedStatementCount();
long getClosedPreparedStatementCount();
long getPreparedStatementCount();
// Statistics management
void resetStat();
boolean isResetStatEnable();
long getResetCount();
DruidDataSourceStatValue getStatValueAndReset();
Map<String, Object> getStatData();
Map<String, Object> getStatDataForMBean();
// SQL statistics
JdbcSqlStat getSqlStat(int sqlId);
JdbcSqlStat getSqlStat(long sqlId);
Map<String, JdbcSqlStat> getSqlStatMap();
// Wall filter statistics
Map<String, Object> getWallStatMap();
WallProviderStatValue getWallStatValue(boolean reset);
// DataSource statistics objects
JdbcDataSourceStat getDataSourceStat();
List<Map<String, Object>> getPoolingConnectionInfo();// Logging and debugging
void logStats();
String dump();
String toString();
String getInitStackTrace();
String getProperties();
// Version information
String getVersion();
// Driver information
Driver getDriver();
void setDriver(Driver driver);
int getDriverMajorVersion();
int getDriverMinorVersion();
int getRawDriverMajorVersion();
int getRawDriverMinorVersion();
// Wrapper support
boolean isWrapperFor(Class<?> iface);
<T> T unwrap(Class<T> iface);// Custom schedulers for advanced use cases
void setCreateScheduler(ScheduledExecutorService scheduler);
void setDestroyScheduler(ScheduledExecutorService scheduler);
void setMaxCreateTaskCount(int count); // Default: 3Druid automatically configures database-specific optimizations:
// MySQL optimization example
dataSource.setDbType("mysql");
dataSource.setValidationQuery("SELECT 1");
dataSource.setExceptionSorterClassName("com.alibaba.druid.pool.vendor.MySqlExceptionSorter");
dataSource.setValidConnectionCheckerClassName("com.alibaba.druid.pool.vendor.MySqlValidConnectionChecker");
// Oracle optimization
dataSource.setDbType("oracle");
dataSource.setValidationQuery("SELECT 1 FROM DUAL");
dataSource.setExceptionSorterClassName("com.alibaba.druid.pool.vendor.OracleExceptionSorter");import com.alibaba.druid.pool.DruidDataSource;
import java.sql.SQLException;
public class DruidDataSourceConfiguration {
public static DruidDataSource createConfiguredDataSource() throws SQLException {
DruidDataSource dataSource = new DruidDataSource();
// Basic connection
dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");
dataSource.setUsername("dbuser");
dataSource.setPassword("dbpass");
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
// Pool configuration
dataSource.setInitialSize(5);
dataSource.setMaxActive(20);
dataSource.setMinIdle(5);
dataSource.setMaxWait(60000);
// Connection validation
dataSource.setValidationQuery("SELECT 1");
dataSource.setTestWhileIdle(true);
dataSource.setTestOnBorrow(false);
dataSource.setTestOnReturn(false);
// Timing configuration
dataSource.setTimeBetweenEvictionRunsMillis(60000);
dataSource.setMinEvictableIdleTimeMillis(300000);
dataSource.setMaxEvictableIdleTimeMillis(900000);
// PreparedStatement pooling
dataSource.setPoolPreparedStatements(true);
dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
// Abandoned connection handling
dataSource.setRemoveAbandoned(true);
dataSource.setRemoveAbandonedTimeout(1800);
dataSource.setLogAbandoned(true);
// Filters for monitoring and security
dataSource.setFilters("stat,wall,slf4j");
// Initialize the DataSource
dataSource.init();
return dataSource;
}
}Common validation includes:
maxActive > 0 and maxActive >= minIdleinitialSize <= maxActivemaxWait >= 0 or -1 for no timeoutCommon exceptions:
SQLException for connection failuresIllegalArgumentException for invalid parametersIllegalStateException for operations on closed DataSourceInstall with Tessl CLI
npx tessl i tessl/maven-com-alibaba--druid