A large part of the Java program needs to operate the database . In order to improve the performance, when operating the database, the database connection pool has to be used. There are many choices for database connection pools, such as c3p, dhcp, proxool, etc. Druid, as a rising star, has gradually entered everyone's attention with its excellent performance. Next, this tutorial will talk about the simple use of druid.
First download the latest jar package from http://repo1.maven.org/maven2/com/alibaba/druid/ . If you want to compile with the latest source code, you can download the source code from https://github.com/alibaba/druid , and then use the maven command line, or import it into eclipse for compilation.
Similar to dbcp, the configuration items of druid are as follows
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, fair locks are enabled by default, and the concurrency efficiency will decrease. If necessary, you can use unfair locks 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 | To enable PSCache, it must be configured with a value greater than 0. When greater than 0, poolPreparedStatements is automatically triggered and modified to true. In Druid, there is no problem that PSCache under Oracle occupies too much memory, you can configure this value to be larger, such as 100 |
validationQuery | The sql used to detect whether the connection is valid requires a query statement. If the validationQuery is null, testOnBorrow, testOnReturn, testWhileIdle will not work. |
|
testOnBorrow | true | When applying for a connection, execute the validationQuery to check whether the connection is valid. This configuration will reduce performance. |
testOnReturn | false | When returning the connection, execute the validationQuery to check whether the connection is valid. This configuration will reduce performance. |
testWhileIdle | false | 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. |
timeBetweenEvictionRunsMillis | There are two meanings: 1) The Destroy thread will detect the connection interval 2) The judgment basis of testWhileIdle, see the description of the testWhileIdle property for details |
|
numTestsPerEvictionRun | No longer used, a DruidDataSource only supports one EvictionRun | |
minEvictableIdleTimeMillis | ||
connectionInitSqls | The sql executed when the physical connection is initialized | |
exceptionSorter | 根据dbType自动识别 | 当数据库抛出一些不可恢复的异常时,抛弃连接 |
filters | 属性类型是字符串,通过别名的方式配置扩展插件, 常用的插件有: 监控统计用的filter:stat 日志用的filter:log4j 防御sql注入的filter:wall |
|
proxyFilters | 类型是List<com.alibaba.druid.filter.Filter>, 如果同时配置了filters和proxyFilters, 是组合关系,并非替换关系 |
表1.1 配置属性
加入 druid-1.0.9.jar
ApplicationContext.xml
< bean name = "transactionManager" class ="org.springframework.jdbc.datasource.DataSourceTransactionManager" >
< property name = "dataSource" ref = "dataSource" ></ property >
</ bean >
< bean id = "propertyConfigurer" class ="org.springframework.beans.factory.config.PropertyPlaceholderConfigurer" >
< property name = "locations" >
< list >
< value > /WEB-INF/classes/dbconfig.properties </ value >
</ list >
</ property >
</ bean >
<!-- 阿里 druid 数据库连接池 -->
< bean id = "dataSource" class = "com.alibaba.druid.pool.DruidDataSource"destroy-method = "close" >
<!-- 数据库基本信息配置 -->
< property name = "url" value = "${url}" />
< property name = "username" value = "${username}" />
< property name = "password" value = "${password}" />
< property name = "driverClassName" value = "${driverClassName}" />
< property name = "filters" value = "${filters}" />
<!-- 最大并发连接数 -->
< property name = "maxActive" value = "${maxActive}" />
<!-- 初始化连接数量 -->
< property name = "initialSize" value = "${initialSize}" />
<!-- 配置获取连接等待超时的时间 -->
< property name = "maxWait" value = "${maxWait}" />
<!-- 最小空闲连接数 -->
< property name = "minIdle" value = "${minIdle}" />
<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
< property name = "timeBetweenEvictionRunsMillis" value ="${timeBetweenEvictionRunsMillis}" />
<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
< property name = "minEvictableIdleTimeMillis" value ="${minEvictableIdleTimeMillis}" />
< property name = "validationQuery" value = "${validationQuery}" />
< property name = "testWhileIdle" value = "${testWhileIdle}" />
< property name = "testOnBorrow" value = "${testOnBorrow}" />
< property name = "testOnReturn" value = "${testOnReturn}" />
< property name = "maxOpenPreparedStatements" value ="${maxOpenPreparedStatements}" />
<!-- 打开 removeAbandoned 功能 -->
< property name = "removeAbandoned" value = "${removeAbandoned}" />
<!-- 1800 秒,也就是 30 分钟 -->
< property name = "removeAbandonedTimeout" value ="${removeAbandonedTimeout}" />
<!-- 关闭 abanded 连接时输出错误日志 -->
< property name = "logAbandoned" value = "${logAbandoned}" />
</ bean >
dbconfig.properties
url: jdbc:MySQL:// localhost :3306/ newm
driverClassName: com.mysql.jdbc.Driver
username: root
password: root
filters: stat
maxActive: 20
initialSize: 1
maxWait: 60000
minIdle: 10
maxIdle: 15
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 'x'
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
maxOpenPreparedStatements: 20
removeAbandoned: true
removeAbandonedTimeout: 1800
logAbandoned: true
web.xml
<!-- 连接池 启用 Web 监控统计功能 start-->
< filter >
< filter-name > DruidWebStatFilter </ filter-name >
< filter-class > com.alibaba.druid.support.http.WebStatFilter </ filter-class >
< init-param >
< param-name > exclusions </ param-name >
< param-value > *. js ,*. gif ,*. jpg ,*. png ,*. css ,*. ico ,/ druid /* </ param-value >
</ init-param >
</ filter >
< filter-mapping >
< filter-name > DruidWebStatFilter </ filter-name >
< url-pattern > /* </ url-pattern >
</ filter-mapping >
< servlet >
< servlet-name > DruidStatView </ servlet-name >
< servlet-class > com.alibaba.druid.support.http.StatViewServlet </ servlet-class >
</ servlet >
< servlet-mapping >
< servlet-name > DruidStatView </ servlet-name >
< url-pattern > / druid /* </ url-pattern >
</ servlet-mapping >
<!-- Connection Pool Enable Web Monitoring Statistics end-->
Visit the monitoring page: http://ip:port/projectName/druid/index.html