pom introduction
<dependency> <groupId>com.alibaba</groupId> <artifactId>druid</artifactId> <version>1.0.18</version> </dependency>
Initialize connection
In the configuration file of druid connecting to the database, there should be "init method =" init "in the bean reading and writing datasource Otherwise, initialization will not be performed when starting the connection pool.
Example:
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> ....... </bean>
Parameter configuration and description
Through the spring configuration file application context The dataSource configuration in XML describes the configuration of various parameters.
attribute | explain | recommended value |
---|---|---|
url | The jdbc connection address of the database. It is generally connected to oracle/mysql. Examples are as follows: | |
mysql : jdbc:mysql://ip:port/dbname?option1&option2&... | ||
oracle : jdbc:oracle:thin:@ip:port:oracle_sid | ||
username | User name to log in to the database | |
password | User password to log in to the database | |
initialSize | How many connections are initialized in the connection pool when the program is started | 10-50 is enough |
maxActive | How many active sessions are supported in the connection pool | |
maxWait | When the program requests a connection from the connection pool, after exceeding the maxWait value, it is considered that the request has failed, that is, the connection pool | 100 |
There is no connection available, in milliseconds. Setting - 1 indicates infinite wait | ||
minEvictableIdleTimeMillis | After the idle time of a connection in the pool reaches N milliseconds, the connection pool will check the idle connection next time | See the description section |
Recycle the connection, which should be less than the firewall timeout setting | ||
net.netfilter.nf_conntrack_tcp_timeout_established settings | ||
timeBetweenEvictionRunsMillis | The frequency of checking idle connections, in milliseconds. Non positive integers mean no checking | |
keepAlive | If the program has no close connection and the idle time exceeds minEvictableIdleTimeMillis, it will execute | true |
Line the SQL specified by validationQuery to ensure that the program connection pool will not be kill ed, and its range does not exceed | ||
The number of connections specified by minIdle is exceeded. | ||
minIdle | When reclaiming idle connections, at least minIdle connections will be guaranteed | Same as initialSize |
removeAbandoned | It is required that the program must close after N seconds after get ting the connection from the pool, otherwise the druid will forcibly recycle the connection | false, when the program is not found |
Connection, regardless of whether the connection is active or idle, to prevent the process from seizing the connection without closing. | Set to true during normal close connection | |
removeAbandonedTimeout | Set the time limit for druid to forcibly reclaim the connection. When the program get s the connection from the pool, it exceeds this limit | It should be longer than the longest service running time |
Value, druid forces the connection to be reclaimed in seconds. | ||
logAbandoned | Whether to record stack trace in the log after druid forcibly reclaims the connection | true |
testWhileIdle | When a program requests a connection, does the pool first check whether the connection is valid when allocating the connection. (high efficiency) | true |
validationQuery |
Check whether the connection in the pool is still available. drui will connect to the database and execute the SQL statement The default values are different for each database: Mysql:SELECT 1; |
|
If it returns normally, it indicates that the connection is available; otherwise, it indicates that the connection is unavailable | ||
testOnBorrow | When the program {applies for} connection, check the connection effectiveness (low efficiency, affecting performance) | false |
testOnReturn | When the program {returns the connection, check the connection effectiveness (low efficiency, affecting performance) | false |
poolPreparedStatements | Cache SQL initiated by the following two methods: | true |
public PreparedStatement prepareStatement(String sql) | ||
public PreparedStatement prepareStatement(String sql, | ||
int resultSetType, int resultSetConcurrency) | ||
maxPoolPrepareStatementPerConnectionSize | How many SQL are cached per connection | 20 |
filters | Plug ins are configured here. Common plug-ins are: | stat,wall,slf4j |
Monitoring statistics: filter:stat | ||
Log monitoring: filter:log4j or slf4j | ||
Defensive SQL injection: filter:wall | ||
connectProperties | Connection properties. For example, set some configuration of connection pool statistics. | |
druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000 | ||
For example, set some database connection properties: | ||
|
matters needing attention
Underlying connection
There is also a parameter accessToUnderlyingConnectionAllowed This parameter sets whether the underlying connection is allowed. If set to true, you can use the following method to obtain the underlying connection:
Connection conn = ds.getConnection(); Connection dconn = ((DelegatingConnection) conn).getInnermostDelegate(); ... conn.close();
false is not enabled by default, because the code logic is incorrect, which may bring risks. It is recommended to use it when you need to directly access the specific functions of the driver, and after many tests, clarify the possible risks of each step of the code.
Idle check problem
When using Ali's SLB, it is recommended to set timebetween evictionrunsmillis to 2 seconds or a negative value (turn off the check mechanism). Otherwise, the connection process will report:
Could not open JDBC Connection for transaction; nested exception is com.mysql.jdbc.exceptions.jdbc4.CommunicaiotnsException: Communications link failure
Different profiles
Spring boot application The configuration in properties is the most complete, which is recommended for reference.
Configuring connection pools in jdbc
jdbc.properties: jdbc.driverClassName=com.mysql.jdbc.Driver jdbc.url=jdbc:mysql://172.49.15.55:3306/testdb?useUnicode=true&characterEncoding=utf-8 jdbc.username=test jdbc.password=test jdbc.filters=stat jdbc.maxActive=300 jdbc.initialSize=2 jdbc.maxWait=60000 jdbc.minIdle=1 jdbc.timeBetweenEvictionRunsMillis=60000 jdbc.minEvictableIdleTimeMillis=300000 jdbc.validationQuery=SELECT 'x' jdbc.testWhileIdle=true jdbc.testOnBorrow=false jdbc.testOnReturn=false jdbc.poolPreparedStatements=false jdbc.maxPoolPreparedStatementPerConnectionSize=50
Configuring druid in spring
<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close"> <!-- "Basic properties of connection --> <property name="url" value="jdbc_url" /> <property name="username" value="${jdbc_user}" /> <property name="password" value="${jdbc_password}" /> <!-- Connection pool properties --> <property name="initialSize" value="100" /> <property name="maxActive" value="1000" /> <property name="maxWait" value="60000" /> <property name="minEvictableIdleTimeMillis" value=300000 /> <property name="keepAlive" value=true /> <property name="timeBetweenEvictionRunsMillis" value=-1 /> <property name="minIdle" value="20" /> <property name="removeAbandoned" value="true"/> <property name="removeAbandonedTimeout" value="180"/> <property name="logAbandoned" value="true" /> <property name="testWhileIdle" value="true" /> <property name="validationQuery" value="SELECT 'x'" /> <property name="testOnBorrow" value="false" /> <property name="testOnReturn" value="false" /> <property name="poolPreparedStatements" value="true"/> <property name="maxPoolPreparedStatementPerConnectionSize" value="20"/> <property name="filters" value="stat,wall,slf4j"/> <property name="connectionProperties" value="druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000" /> </bean>
spring boot application.properties configuration
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource #Driver configuration information spring.datasource.driver-class-name=com.mysql.jdbc.Driver #Basic connection information spring.datasource.username = root spring.datasource.password = root spring.datasource.url=jdbc:mysql://192.168.153.23:3306/mytest?useUnicode=true&characterEncoding=utf-8 #Connection pool properties spring.datasource.druid.initial-size=15 spring.datasource.druid.max-active=100 spring.datasource.druid.min-idle=15 spring.datasource.druid.max-wait=60000 spring.datasource.druid.time-between-eviction-runs-millis=60000 spring.datasource.druid.min-evictable-idle-time-millis=300000 spring.datasource.druid.test-on-borrow=false spring.datasource.druid.test-on-return=false spring.datasource.druid.test-while-idle=true spring.datasource.druid.validation-query=SELECT 1 spring.datasource.druid.validation-query-timeout=1000 spring.datasource.druid.keep-alive=true spring.datasource.druid.remove-abandoned=true spring.datasource.druid.remove-abandoned-timeout=180 spring.datasource.druid.log-abandoned=true spring.datasource.druid.pool-prepared-statements=true spring.datasource.druid.max-pool-prepared-statement-per-connection-size=20 spring.datasource.druid.filters=stat,wall,slf4j spring.datasource.druid.use-global-data-source-stat=true spring.datasource.druid.preparedStatement=true spring.datasource.druid.maxOpenPreparedStatements=100 spring.datasource.druid.connect-properties.mergeSql=true spring.datasource.druid.connect-properties.slowSqlMillis=5000
Transferred from: https://www.cnblogs.com/halberd-lee/p/11304790.html