0
# DataSource Configuration
1
2
Complete guide to configuring Druid DataSource for JDBC connection pooling with comprehensive parameter control and optimization options.
3
4
## Core Configuration
5
6
### Creating DataSource Instances
7
8
```java { .api }
9
// Constructor-based creation
10
DruidDataSource dataSource = new DruidDataSource();
11
DruidDataSource dataSource = new DruidDataSource(boolean fairLock);
12
13
// Factory-based creation
14
DataSource dataSource = DruidDataSourceFactory.createDataSource(Properties properties);
15
DataSource dataSource = DruidDataSourceFactory.createDataSource(Map<String, Object> properties);
16
```
17
18
### Basic Connection Properties
19
20
```java { .api }
21
// Essential connection configuration
22
void setUrl(String jdbcUrl);
23
void setUsername(String username);
24
void setPassword(String password);
25
void setDriverClassName(String driverClass);
26
void setDriverClassLoader(ClassLoader classLoader);
27
void setConnectProperties(Properties properties);
28
void setConnectionProperties(String connectionProperties);
29
30
// Connection behavior
31
void setDefaultAutoCommit(Boolean autoCommit);
32
void setDefaultReadOnly(Boolean readOnly);
33
void setDefaultTransactionIsolation(Integer isolationLevel);
34
void setDefaultCatalog(String catalog);
35
```
36
37
## Connection Pool Configuration
38
39
### Pool Size Management
40
41
```java { .api }
42
// Pool sizing parameters
43
void setInitialSize(int initialSize); // Default: 0
44
void setMaxActive(int maxActive); // Default: 8
45
void setMinIdle(int minIdle); // Default: 0
46
void setMaxIdle(int maxIdle); // Deprecated
47
48
// Connection acquisition
49
void setMaxWait(long maxWaitMillis); // Default: -1 (no timeout)
50
void setMaxWaitThreadCount(int maxWaitThreadCount);
51
void setNotFullTimeoutRetryCount(int count);
52
```
53
54
### Connection Lifecycle Timing
55
56
```java { .api }
57
// Eviction timing controls
58
void setTimeBetweenEvictionRunsMillis(long millis); // Default: 60000ms
59
void setMinEvictableIdleTimeMillis(long millis); // Default: 30min
60
void setMaxEvictableIdleTimeMillis(long millis); // Default: 7h
61
62
// Connection lifecycle
63
void setKeepAliveBetweenTimeMillis(long millis);
64
void setPhyTimeoutMillis(long millis);
65
void setPhyMaxUseCount(long count);
66
67
// Timeout configuration
68
void setConnectTimeout(int milliseconds); // Default: 10000ms
69
void setSocketTimeout(int milliseconds); // Default: 10000ms
70
void setQueryTimeout(int seconds);
71
void setTransactionQueryTimeout(int seconds);
72
```
73
74
## Connection Validation
75
76
### Validation Configuration
77
78
```java { .api }
79
// Validation query setup
80
void setValidationQuery(String query);
81
void setValidationQueryTimeout(int timeout);
82
void setValidConnectionChecker(ValidConnectionChecker checker);
83
void setValidConnectionCheckerClassName(String className);
84
85
// Test timing configuration
86
void setTestOnBorrow(boolean test); // Default: false
87
void setTestOnReturn(boolean test); // Default: false
88
void setTestWhileIdle(boolean test); // Default: true
89
```
90
91
### Connection Testing Usage
92
93
```java
94
// Example validation configuration
95
dataSource.setValidationQuery("SELECT 1");
96
dataSource.setValidationQueryTimeout(5);
97
dataSource.setTestWhileIdle(true);
98
dataSource.setTestOnBorrow(false);
99
dataSource.setTimeBetweenEvictionRunsMillis(60000);
100
```
101
102
## PreparedStatement Pooling
103
104
```java { .api }
105
// PreparedStatement caching
106
void setPoolPreparedStatements(boolean pool);
107
void setMaxPoolPreparedStatementPerConnectionSize(int size); // Default: 10
108
void setSharePreparedStatements(boolean share);
109
```
110
111
## Error Handling and Recovery
112
113
### Abandoned Connection Management
114
115
```java { .api }
116
// Abandoned connection detection
117
void setRemoveAbandoned(boolean remove);
118
void setRemoveAbandonedTimeout(int timeout); // Seconds
119
void setRemoveAbandonedTimeoutMillis(long millis);
120
void setLogAbandoned(boolean log);
121
```
122
123
### Connection Error Recovery
124
125
```java { .api }
126
// Error recovery configuration
127
void setConnectionErrorRetryAttempts(int attempts); // Default: 1
128
void setBreakAfterAcquireFailure(boolean breakAfter);
129
void setTimeBetweenConnectErrorMillis(long millis); // Default: 500ms
130
void setExceptionSorter(ExceptionSorter sorter);
131
void setExceptionSorterClassName(String className);
132
```
133
134
## Advanced Configuration
135
136
### Performance and Behavior
137
138
```java { .api }
139
// Performance tuning
140
void setAsyncInit(boolean async);
141
void setKeepAlive(boolean keepAlive);
142
void setUseUnfairLock(boolean unfair); // Default: true
143
void setFailFast(boolean failFast);
144
void setKillWhenSocketReadTimeout(boolean kill);
145
146
// Filter configuration
147
void setFilters(String filters); // e.g., "stat,wall,log4j"
148
void setProxyFilters(List<Filter> filters);
149
void setClearFiltersEnable(boolean enable);
150
```
151
152
### Initialization and Custom SQL
153
154
```java { .api }
155
// Connection initialization
156
void setConnectionInitSqls(Collection<String> sqls);
157
void setInitVariants(boolean init);
158
void setInitGlobalVariants(boolean init);
159
void setInitExceptionThrow(boolean throwException);
160
```
161
162
## DataSource Lifecycle Management
163
164
### Initialization and Cleanup
165
166
```java { .api }
167
// Lifecycle management
168
void init() throws SQLException;
169
void close();
170
void restart() throws SQLException;
171
void restart(Properties properties) throws SQLException;
172
173
// Runtime management
174
boolean isClosed();
175
boolean isEnable();
176
void setEnable(boolean enable);
177
int fill() throws SQLException;
178
int fill(int toCount) throws SQLException;
179
void shrink();
180
void shrink(boolean checkTime);
181
void shrink(boolean checkTime, boolean keepAlive);
182
void clearStatementCache() throws SQLException;
183
int removeAbandoned();
184
boolean isFull();
185
```
186
187
### Connection Retrieval Methods
188
189
```java { .api }
190
// Standard connection methods
191
Connection getConnection() throws SQLException;
192
Connection getConnection(String username, String password) throws SQLException;
193
DruidPooledConnection getConnection(long maxWaitMillis) throws SQLException;
194
195
// Direct and advanced connection methods
196
DruidPooledConnection getConnectionDirect(long maxWaitMillis) throws SQLException;
197
DruidPooledConnection tryGetConnection() throws SQLException;
198
boolean discardConnection(Connection conn);
199
200
// PooledConnection interface methods
201
PooledConnection getPooledConnection() throws SQLException;
202
PooledConnection getPooledConnection(String user, String password) throws SQLException;
203
```
204
205
### Runtime Configuration Management
206
207
```java { .api }
208
// Configuration from properties
209
void configFromProperties(Properties properties);
210
211
// Filter management
212
void addFilters(String filters) throws SQLException;
213
void clearFilters();
214
List<Filter> getProxyFilters();
215
List<String> getFilterClassNames();
216
217
// MBean management
218
void registerMbean();
219
void unregisterMbean();
220
boolean isMbeanRegistered();
221
ObjectName getObjectName();
222
void setObjectName(ObjectName objectName);
223
```
224
225
## Property-Based Configuration
226
227
### Configuration Properties
228
229
```java
230
// Properties-based configuration example
231
Properties config = new Properties();
232
config.setProperty("url", "jdbc:mysql://localhost:3306/test");
233
config.setProperty("username", "root");
234
config.setProperty("password", "password");
235
config.setProperty("driverClassName", "com.mysql.cj.jdbc.Driver");
236
237
// Pool configuration
238
config.setProperty("initialSize", "5");
239
config.setProperty("maxActive", "20");
240
config.setProperty("minIdle", "5");
241
config.setProperty("maxWait", "60000");
242
243
// Validation
244
config.setProperty("validationQuery", "SELECT 1");
245
config.setProperty("testWhileIdle", "true");
246
config.setProperty("testOnBorrow", "false");
247
248
// Timing
249
config.setProperty("timeBetweenEvictionRunsMillis", "60000");
250
config.setProperty("minEvictableIdleTimeMillis", "300000");
251
252
// Features
253
config.setProperty("poolPreparedStatements", "true");
254
config.setProperty("maxPoolPreparedStatementPerConnectionSize", "20");
255
config.setProperty("filters", "stat,wall,slf4j");
256
257
// Create DataSource
258
DataSource dataSource = DruidDataSourceFactory.createDataSource(config);
259
```
260
261
## Statistics and Monitoring Configuration
262
263
```java { .api }
264
// Statistics configuration
265
void setTimeBetweenLogStatsMillis(long millis);
266
void setStatLogger(DruidDataSourceStatLogger logger);
267
void setStatLoggerClassName(String className);
268
void setResetStatEnable(boolean enable);
269
void setTransactionThresholdMillis(long millis);
270
271
// Monitoring setup
272
void setName(String name); // DataSource name for monitoring
273
void setDbType(String dbType); // Database type hint
274
void setUseGlobalDataSourceStat(boolean global);
275
```
276
277
### Statistics Retrieval Methods
278
279
```java { .api }
280
// Connection pool statistics
281
long getCreateCount();
282
long getDestroyCount();
283
long getConnectCount();
284
long getCloseCount();
285
long getConnectErrorCount();
286
long getErrorCount();
287
long getRecycleCount();
288
long getRecycleErrorCount();
289
long getDiscardCount();
290
291
// Pool state statistics
292
int getPoolingCount();
293
int getActiveCount();
294
int getActivePeak();
295
Date getActivePeakTime();
296
int getPoolingPeak();
297
Date getPoolingPeakTime();
298
299
// Wait thread statistics
300
int getWaitThreadCount();
301
long getNotEmptyWaitCount();
302
int getNotEmptyWaitThreadCount();
303
int getNotEmptyWaitThreadPeak();
304
long getNotEmptySignalCount();
305
long getNotEmptyWaitMillis();
306
long getNotEmptyWaitNanos();
307
308
// Execution statistics
309
long getExecuteCount();
310
long getExecuteUpdateCount();
311
long getExecuteQueryCount();
312
long getExecuteBatchCount();
313
long getCommitCount();
314
long getRollbackCount();
315
long getStartTransactionCount();
316
317
// PreparedStatement statistics
318
long getCachedPreparedStatementHitCount();
319
long getCachedPreparedStatementMissCount();
320
long getCachedPreparedStatementAccessCount();
321
long getCachedPreparedStatementDeleteCount();
322
long getCachedPreparedStatementCount();
323
long getClosedPreparedStatementCount();
324
long getPreparedStatementCount();
325
326
// Statistics management
327
void resetStat();
328
boolean isResetStatEnable();
329
long getResetCount();
330
DruidDataSourceStatValue getStatValueAndReset();
331
Map<String, Object> getStatData();
332
Map<String, Object> getStatDataForMBean();
333
334
// SQL statistics
335
JdbcSqlStat getSqlStat(int sqlId);
336
JdbcSqlStat getSqlStat(long sqlId);
337
Map<String, JdbcSqlStat> getSqlStatMap();
338
339
// Wall filter statistics
340
Map<String, Object> getWallStatMap();
341
WallProviderStatValue getWallStatValue(boolean reset);
342
343
// DataSource statistics objects
344
JdbcDataSourceStat getDataSourceStat();
345
List<Map<String, Object>> getPoolingConnectionInfo();
346
```
347
348
### Management and Debugging Methods
349
350
```java { .api }
351
// Logging and debugging
352
void logStats();
353
String dump();
354
String toString();
355
String getInitStackTrace();
356
String getProperties();
357
358
// Version information
359
String getVersion();
360
361
// Driver information
362
Driver getDriver();
363
void setDriver(Driver driver);
364
int getDriverMajorVersion();
365
int getDriverMinorVersion();
366
int getRawDriverMajorVersion();
367
int getRawDriverMinorVersion();
368
369
// Wrapper support
370
boolean isWrapperFor(Class<?> iface);
371
<T> T unwrap(Class<T> iface);
372
```
373
374
## Scheduler Configuration
375
376
```java { .api }
377
// Custom schedulers for advanced use cases
378
void setCreateScheduler(ScheduledExecutorService scheduler);
379
void setDestroyScheduler(ScheduledExecutorService scheduler);
380
void setMaxCreateTaskCount(int count); // Default: 3
381
```
382
383
## Database-Specific Optimizations
384
385
Druid automatically configures database-specific optimizations:
386
387
```java
388
// MySQL optimization example
389
dataSource.setDbType("mysql");
390
dataSource.setValidationQuery("SELECT 1");
391
dataSource.setExceptionSorterClassName("com.alibaba.druid.pool.vendor.MySqlExceptionSorter");
392
dataSource.setValidConnectionCheckerClassName("com.alibaba.druid.pool.vendor.MySqlValidConnectionChecker");
393
394
// Oracle optimization
395
dataSource.setDbType("oracle");
396
dataSource.setValidationQuery("SELECT 1 FROM DUAL");
397
dataSource.setExceptionSorterClassName("com.alibaba.druid.pool.vendor.OracleExceptionSorter");
398
```
399
400
## Complete Configuration Example
401
402
```java
403
import com.alibaba.druid.pool.DruidDataSource;
404
import java.sql.SQLException;
405
406
public class DruidDataSourceConfiguration {
407
public static DruidDataSource createConfiguredDataSource() throws SQLException {
408
DruidDataSource dataSource = new DruidDataSource();
409
410
// Basic connection
411
dataSource.setUrl("jdbc:mysql://localhost:3306/mydb");
412
dataSource.setUsername("dbuser");
413
dataSource.setPassword("dbpass");
414
dataSource.setDriverClassName("com.mysql.cj.jdbc.Driver");
415
416
// Pool configuration
417
dataSource.setInitialSize(5);
418
dataSource.setMaxActive(20);
419
dataSource.setMinIdle(5);
420
dataSource.setMaxWait(60000);
421
422
// Connection validation
423
dataSource.setValidationQuery("SELECT 1");
424
dataSource.setTestWhileIdle(true);
425
dataSource.setTestOnBorrow(false);
426
dataSource.setTestOnReturn(false);
427
428
// Timing configuration
429
dataSource.setTimeBetweenEvictionRunsMillis(60000);
430
dataSource.setMinEvictableIdleTimeMillis(300000);
431
dataSource.setMaxEvictableIdleTimeMillis(900000);
432
433
// PreparedStatement pooling
434
dataSource.setPoolPreparedStatements(true);
435
dataSource.setMaxPoolPreparedStatementPerConnectionSize(20);
436
437
// Abandoned connection handling
438
dataSource.setRemoveAbandoned(true);
439
dataSource.setRemoveAbandonedTimeout(1800);
440
dataSource.setLogAbandoned(true);
441
442
// Filters for monitoring and security
443
dataSource.setFilters("stat,wall,slf4j");
444
445
// Initialize the DataSource
446
dataSource.init();
447
448
return dataSource;
449
}
450
}
451
```
452
453
## Validation and Error Patterns
454
455
Common validation includes:
456
- `maxActive > 0` and `maxActive >= minIdle`
457
- `initialSize <= maxActive`
458
- `maxWait >= 0` or `-1` for no timeout
459
- Valid JDBC URL format
460
- Driver class availability
461
- Database connectivity verification
462
463
Common exceptions:
464
- `SQLException` for connection failures
465
- `IllegalArgumentException` for invalid parameters
466
- `IllegalStateException` for operations on closed DataSource