Druid database connection pool usage

I have been using DBCP and C3P0 connection pools for a period of time before, and the operation stability is still OK, but it is occasionally disconnected, but it does not need to be reconnected, it is automatically connected. Later, more and more people use Ali's druid connection pool. The official test data is also quite powerful, and the performance is much better. At the same time, the Druid connection pool is equipped with a monitoring function, which can monitor the execution time of the platform's SQL statements, etc. It does feel more intuitive and powerful in many aspects.

 

Simply record the configuration druid process:

 

Dependency jar package:

 

<!-- druid -->
<dependency>
   <groupId>com.alibaba</groupId>
   <artifactId>druid</artifactId>
   <version>1.0.7</version>
</dependency>

 

 

1. Data source replacement

 

	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		destroy-method="close">
		<!-- jdbc basic information configuration-->
		<property name="driverClassName" value="${jdbc.driverClassName}"></property>
		<property name="url" value="${jdbc.url}"></property>
		<property name="username" value="${jdbc.username}"></property>
		<property name="password" value="${jdbc.password}"></property>
	
		<!-- Configure initialization size, minimum, maximum -->
		<property name="initialSize" value="${jdbc.pool.initialSize}" />
		<property name="minIdle" value="${jdbc.pool.minIdle}" />
		<property name="maxActive" value="${jdbc.pool.maxActive}" />
		<!-- Configure the time unit in milliseconds for getting a connection to wait for timeout-->
		<property name="maxWait" value="${jdbc.pool.maxWait}" />

		<!-- How long is the configuration interval to perform detection, and detect idle connections that need to be closed, in milliseconds-->
		<property name="timeBetweenEvictionRunsMillis" value="60000" />
		<!-- SQL to verify whether the connection is valid or not, different data configurations are different mysql select 1 || oracle select 1 from dual-->
		<property name="validationQuery" value="select 1 " />
		<!-- Configure the minimum lifetime of a connection in the pool, in milliseconds-->
		<property name="minEvictableIdleTimeMillis" value="300000" />
		<!-- It is recommended to configure it to true, which does not affect performance and ensures security. Detect when applying for a connection. If the idle time is greater than timeBetweenEvictionRunsMillis, execute validationQuery to check whether the connection is valid. -->
		<property name="testWhileIdle" value="true" />
		<!-- When applying for a connection, execute the validationQuery to check whether the connection is valid. This configuration will reduce performance. -->
		<property name="testOnBorrow" value="false" />
		<!-- When returning the connection, execute the validationQuery to check whether the connection is valid. This configuration will reduce performance -->
		<property name="testOnReturn" value="false" />
		<!-- Open PSCache and specify the size of PSCache on each connection. PSCache greatly improves the performance of databases that support cursors, such as oracle. It is recommended to close under mysql. -->
		<property name="poolPreparedStatements" value="false" />
		<property name="maxPoolPreparedStatementPerConnectionSize"
			value="20" />
		 <!-- There is jdbcSqlStat in monitoring, the reason is: in the createSqlStat method in com.alibaba.druid.statJdbcDataSourceStat,
            A map is used to store all sql statements, which will trigger FullGC online, you can comment out here -->
		<property name="filters" value="stat,wall,log4j" />
		<!-- Mapping slow sql -->
		<property name="proxyFilters">
			<list>
				<ref bean="statfilter" />
				<ref bean="logFilter" />
			</list>
		</property>
	</bean>

 

2. Add druid sql filter to monitor slow sql

 

     <!-- Slow SQL logging -->
	<bean id="statfilter" class="com.alibaba.druid.filter.stat.StatFilter">
		<!-- Open merge sql -->
		<property name="mergeSql" value="true" />
		<!-- Enable slow query statement, 1000 milliseconds-->
		<property name="slowSqlMillis" value="1000" />
		<property name="logSlowSql" value="true" />
	</bean>
	
	<bean id="logFilter" class="com.alibaba.druid.filter.logging.Log4jFilter">
        <property name="resultSetLogEnabled" value="false" />
        <property name="statementExecutableSqlLogEnable" value="true" />
    </bean>

 

3.jdbc.properties

 

jdbc.driverClassName=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8
jdbc.username=root
jdbc.password=123456
jdbc.pool.initialSize=1
jdbc.pool.minIdle=1
jdbc.pool.maxActive=10
jdbc.pool.maxWait=30000

 

 

4.web.xml configure servlet and filter

 

 

<!-- Turn on druid stat filtering, WebStatFilter is used to collect web-jdbc related monitoring data, pay attention to put it in front of other filters and dispatchers, it is very heavy-->
    <filter>
        <filter-name>druidWebStatFilter</filter-name>
        <filter-class>com.alibaba.druid.support.http.WebStatFilter</filter-class>
		<!-- Exclude static resources -->
        <init-param>
            <param-name>exclusions</param-name>
            <param-value>/public/*,*.js,*.css,/druid*,*.jsp,*.swf</param-value>
        </init-param>
	<!-- druid can know the user of the current session, according to the needs, modify the xxx.user in it to the sessionName where your user information is stored in the session. -->
        <init-param>
            <param-name>principalSessionName</param-name>
            <param-value>session.user</param-value>
        </init-param>
         <!-- Druid 0.2.7 version supports profiles, configure profileEnable to monitor the sql list of a single url call -->
        <init-param>
            <param-name>profileEnable</param-name>
            <param-value>true</param-value>
        </init-param>
    </filter>
    <filter-mapping>
        <filter-name>druidWebStatFilter</filter-name>
        <url-pattern>/*</url-pattern>
    </filter-mapping>
	<!-- druid monitoring platform monitor -->
	<servlet>
        <servlet-name>DruidStatView</servlet-name>
        <servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
        <init-param>
            <!-- Allow clearing statistics-->
            <param-name>resetEnable</param-name>
            <param-value>true</param-value>
        </init-param>
		<!-- The possibility of the website being attacked is very high, and the security is not guaranteed, so it is recommended to configure the account information. -->
        <init-param>
            <!-- username-->
            <param-name>loginUsername</param-name>
            <param-value>druid</param-value>
        </init-param>
        <init-param>
            <!-- password-->
            <param-name>loginPassword</param-name>
            <param-value>druid</param-value>
        </init-param>
    </servlet>
	<!-- route map address-->
    <servlet-mapping>
        <servlet-name>DruidStatView</servlet-name>
        <url-pattern>/druid/*</url-pattern>
    </servlet-mapping>

 

 

 

 5. Log configuration

 

###Display the SQL statement part of this project, com.test is the basic package of the project, print the execution sql and configure druid to print the query result
log4j.logger.com.test=DEBUG
log4j.logger.druid.sql.ResultSet=DEBUG

 

 6. Detailed explanation of druid configuration

       

configure Default value illustrate
name   The significance of configuring this property is that if there are multiple data sources, they 
can be distinguished by name when monitoring. If not configured, a name will be generated in the 
format: "DataSource-" + System.identityHashCode(this)
jdbcUrl   The url to connect to the database is different for different databases. For example: 
mysql : jdbc:mysql://10.20.153.104:3306/druid2  
oracle : jdbc:oracle:thin:@10.20.149.85:1521:ocnauto
username   Username to connect to the database
password   Password to connect to the database. If you don't want the password to be written directly in the configuration file, 
you can use ConfigFilter. See here for details: 
https://github.com/alibaba/druid/wiki/%E4%BD%BF%E7%94%A8ConfigFilter
driverClassName Automatically identify by url This item can be matched or not. If druid is not configured, the dbType will be automatically recognized according to the url, and then the corresponding driverClassName will be selected.
initialSize 0 The number of physical connections established during initialization. Initialization occurs when the init method is explicitly called, or the first time getConnection
maxActive 8 Maximum number of connection pools
maxIdle 8 It is no longer used, and the configuration has no effect
minIdle   Minimum number of connection pools
maxWait   The maximum wait time when getting a connection, in milliseconds. After maxWait is configured, the 
fair lock is enabled by default, and the concurrency efficiency will be reduced. 
If necessary, you can use the unfair lock by configuring the useUnfairLock property to true.
halfPreparedStatements false Whether to cache preparedStatement, which is PSCache. 
PSCache greatly improves the performance of databases that support cursors, such as oracle. 
There is no PSCache function in versions below mysql5.5, it is recommended to close it.
The author used PSCache in version 5.5, and found that PSCache has a cache hit rate record through the monitoring interface, 
which should support PSCache.
maxOpenPreparedStatements -1 要启用PSCache,必须配置大于0,当大于0时, 
poolPreparedStatements自动触发修改为true。 
在Druid中,不会存在Oracle下PSCache占用内存过多的问题, 
可以把这个数值配置大一些,比如说100
validationQuery   用来检测连接是否有效的sql,要求是一个查询语句。 
如果validationQuery为null,testOnBorrow、testOnReturn、 
testWhileIdle都不会其作用。
testOnBorrow true 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。
testOnReturn false 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能
testWhileIdle false 建议配置为true,不影响性能,并且保证安全性。 
申请连接的时候检测,如果空闲时间大于 
timeBetweenEvictionRunsMillis, 
执行validationQuery检测连接是否有效。
timeBetweenEvictionRunsMillis   有两个含义: 
1) Destroy线程会检测连接的间隔时间 
2) testWhileIdle的判断依据,详细看testWhileIdle属性的说明
numTestsPerEvictionRun   不再使用,一个DruidDataSource只支持一个EvictionRun
minEvictableIdleTimeMillis    
connectionInitSqls   物理连接初始化的时候执行的sql
exceptionSorter 根据dbType自动识别 当数据库抛出一些不可恢复的异常时,抛弃连接
filters   属性类型是字符串,通过别名的方式配置扩展插件, 
常用的插件有: 
监控统计用的filter:stat  
日志用的filter:log4j 
防御sql注入的filter:wall
proxyFilters   类型是List<com.alibaba.druid.filter.Filter>, 
如果同时配置了filters和proxyFilters, 
是组合关系,并非替换关系

7.测试访问

 

访问监控页面: http://ip:port/projectName/druid/index.html



 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326073207&siteId=291194637