Database connection pool Druid configuration and use

For druid configuration information, see the official document DruidDataSource configuration property list

configuration Defaults illustrate
name The significance of configuring this property is that if there are multiple data sources, they can be distinguished by name during monitoring. If not configured, a name will be generated in the format: "DataSource-" + System.identityHashCode(this)
jdbcUrl url to connect to the database
username The 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 the example of using ConfigFilter on the official website
driverClassName Automatic identification based on url Optional, if you do not configure druid, it will automatically identify the dbType according to the url, and then select the corresponding driverClassName (recommended configuration)
initialSize 0 The number of physical connections established during initialization. Initialization occurs when the init method is called explicitly, or when getConnection is first
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 waiting time when obtaining a connection, in milliseconds. After maxWait is configured, the fair lock is enabled by default, and the concurrency efficiency will decrease. If necessary, you can use the unfair lock by configuring the useUnfairLock attribute to true
poolPreparedStatements false Whether to cache preparedStatement, that is, PSCache. PSCache greatly improves the performance of databases that support cursors, such as oracle. It is recommended to close under mysql
maxOpenPreparedStatements -1 To enable PSCache, the configuration must be greater than 0. When it is greater than 0, poolPreparedStatements will be automatically triggered and changed to true. In Druid, there will be no problem of PSCache occupying too much memory under Oracle. You can configure this value to be larger, for example, 100
validationQuery The sql used to check whether the connection is valid requires a query statement. If validationQuery is null, testOnBorrow, testOnReturn, testWhileIdle will not work
testOnBorrow true Execute validationQuery to check whether the connection is valid when applying for a connection. Doing this configuration will reduce performance
testOnReturn false Execute validationQuery to check whether the connection is valid when returning the connection. Doing this configuration will reduce performance
testWhileIdle false It is recommended to configure it as true, which will not affect performance and ensure security. Check 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 attribute for details
numTestsPerEvictionRun No longer used, a DruidDataSource only supports one EvictionRun
minEvictableIdleTimeMills
connectionInitSqls The sql executed when the physical connection is initialized
exceptionSorter Automatic identification based on dbType Abandon the connection when the database throws some unrecoverable exception
filters The attribute type is a string, and the extension plug-in is configured through an alias. Commonly used plug-ins include: filter for monitoring statistics: filter for stat logs: log4j filter for preventing SQL injection: wall
proxyFilters The type is List<com.alibaba.druid.filter.Filter>, if filters and proxyFilters are configured at the same time, it is a combination relationship, not a replacement relationship

1. Integrate Druid in Spring

Introduce Druid dependency

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid</artifactId>
			<version>1.1.6</version>
		</dependency>

Configure jdbc.properties

# 数据库驱动
jdbc.driverClassName=com.mysql.cj.jdbc.Driver
# 数据库连接
jdbc.url=jdbc:mysql:///ssm?useSSL=false&characterEncoding=utf8&serverTimezone=Asia/Shanghai
# 数据库用户名
jdbc.username=hqh
# 数据库密码
jdbc.password=Mysql123
#别名方式,扩展插件,监控统计用的filter:stat,日志用的filter:log4j,防御sql注入的filter:wall
jdbc.filters=stat 
#最大连接数
jdbc.maxActive=300
#初始化连接数
jdbc.initialSize=2
#获取连接最大等待时间
jdbc.maxWait=60000
#最小连接数
jdbc.minIdle=1
#检测连接有效性的时间间隔
jdbc.timeBetweenEvictionRunsMillis=60000
#连接保持空闲而不被驱逐的最长时间
jdbc.minEvictableIdleTimeMillis=300000
#连接有效性,检测sql
jdbc.validationQuery=SELECT 'x'
#定时检测空闲连接有效性
jdbc.testWhileIdle=true
#检测获取的连接的有效性
jdbc.testOnBorrow=false
#检测要归还的连接的有效性
jdbc.testOnReturn=false
#是否缓存preparedStatement,即PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
jdbc.poolPreparedStatements=false
jdbc.maxOpenPreparedStatements=50

Configure data source

	<!--配置数据库连接池(选用druid) -->
	<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource"
		init-method="init" destroy-method="close">
		<!--配置连接池属性 -->

		<!--配置驱动类名字 -->
		<property name="driverClassName" value="${jdbc.driverClassName}" />

		<!-- 基本属性 url、user、password -->
		<property name="url" value="${jdbc.url}" />
		<property name="username" value="${jdbc.username}" />
		<property name="password" value="${jdbc.password}" />

		<!-- 配置初始化大小、最小、最大 -->
		<property name="initialSize" value="${jdbc.initialSize}" />
		<property name="minIdle" value="${jdbc.minIdle}" />
		<property name="maxActive" value="${jdbc.maxActive}" />

		<!-- 配置获取连接等待超时的时间 -->
		<property name="maxWait" value="${jdbc.maxWait}" />

		<!-- 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒 -->
		<property name="timeBetweenEvictionRunsMillis" value="${jdbc.timeBetweenEvictionRunsMillis}" />

		<!-- 配置一个连接在池中最小生存的时间,单位是毫秒 -->
		<property name="minEvictableIdleTimeMillis" value="${jdbc.minEvictableIdleTimeMillis}" />
		
		<!-- 验证连接有效与否的SQL,不同的数据配置不同 -->
		<property name="validationQuery" value="${jdbc.validationQuery}" />
		
		<!-- 建议配置为true,不影响性能,并且保证安全性。申请连接的时候检测,如果空闲时间大于timeBetweenEvictionRunsMillis,执行validationQuery检测连接是否有效。 -->
		<property name="testWhileIdle" value="${jdbc.testWhileIdle}" />
		
		<!-- 这里建议配置为TRUE,防止取到的连接不可用,但会影响性能 -->
		<property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
		
		<!-- 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 -->
		<property name="testOnReturn" value="${jdbc.testOnReturn}" />

		<!-- 打开PSCache,并且指定每个连接上PSCache的大小 。 -->
		<!-- 是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql5.5以下的版本中没有PSCache功能,建议关闭掉。5.5及以上版本有PSCache,建议开启。 -->
		<!-- 要启用PSCache,必须配置大于0,当大于0时,poolPreparedStatements自动触发修改为true。在Druid中,不会存在Oracle下PSCache占用内存过多的问题,可以把这个数值配置大一些,比如说100 -->
		<property name="poolPreparedStatements" value="${jdbc.poolPreparedStatements}" />
		<property name="maxOpenPreparedStatements" value="${jdbc.maxOpenPreparedStatements}" />

		<!-- 配置监控统计拦截的filters,去掉后监控界面sql无法统计 开启web监控、开启sql防火墙 -->
		<property name="filters" value="${jdbc.filters}" />

		<property name="proxyFilters">
			<list>
				<ref bean="logFilter" />
				<ref bean="statFilter" />
			</list>
		</property>
	</bean>

	<!-- 慢SQL记录 -->
	<bean id="statFilter" class="com.alibaba.druid.filter.stat.StatFilter">
		<!-- 慢sql时间设置,即执行时间大于200毫秒的都是慢sql -->
		<property name="slowSqlMillis" value="5" />
		<property name="logSlowSql" value="true" />
	</bean>

	<bean id="logFilter" class="com.alibaba.druid.filter.logging.Slf4jLogFilter">
		<property name="statementExecutableSqlLogEnable" value="false" />
	</bean>

Configure web.xml

	<!-- 配置druid监控 -->
	<servlet>
		<servlet-name>DruidStatView</servlet-name>
		<servlet-class>com.alibaba.druid.support.http.StatViewServlet</servlet-class>
		<init-param>
			<!-- 允许清空统计数据 -->
			<param-name>resetEnable</param-name>
			<param-value>true</param-value>
		</init-param>
		<init-param>
			<!-- 用户名 -->
			<param-name>loginUsername</param-name>
			<param-value>druid</param-value>
		</init-param>
		<init-param>
			<!-- 密码 -->
			<param-name>loginPassword</param-name>
			<param-value>123456</param-value>
		</init-param>
		<!-- deny优先于allow,如果在deny列表中,就算在allow列表中,也会被拒绝。 如果allow没有配置或者为空,则允许所有访问 
			ip配置规则 <IP>或者<IP>/<SUB_NET_MASK_size>,如128.242.127.1/24,不支持IPV6 详情见:https://github.com/alibaba/druid/wiki/%E9%85%8D%E7%BD%AE_StatViewServlet%E9%85%8D%E7%BD%AE -->
		<!-- <init-param> <param-name>allow</param-name> 访问IP白名单 <param-value>*</param-value> 
			</init-param> <init-param> <param-name>deny</param-name> 访问IP黑名单 <param-value></param-value> 
			</init-param> -->
	</servlet>
	<servlet-mapping>
		<servlet-name>DruidStatView</servlet-name>
		<url-pattern>/druid/*</url-pattern>
	</servlet-mapping>

	<!-- WebStatFilter用于采集web-jdbc关联监控的数据,排除一些不必要的url -->
	<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>

For the running result, enter http://localhost:8080/xxxx/druid/index.html, as shown in
insert image description here
the monitoring interface after login
insert image description here

2. Integrate Druid in Spring Boot

Method 1: Directly import druid-spring-boot-starter, refer to druid-spring-boot-starter

		<dependency>
			<groupId>com.alibaba</groupId>
			<artifactId>druid-spring-boot-starter</artifactId>
			<version>1.1.16</version>
		</dependency>

Add the following configuration to application.properties and it will work

#####jdbc配置
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&characterEncoding=utf8&serverTimezone=GMT
spring.datasource.username=hqh
spring.datasource.password=Mysql123
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

#####datasource druid pool
spring.datasource.druid.initial-size=1
spring.datasource.druid.max-active=20
spring.datasource.druid.min-idle=1
spring.datasource.druid.filters=stat
spring.datasource.druid.max-wait=60000
spring.datasource.druid.pool-prepared-statements=true
spring.datasource.druid.max-pool-prepared-statement-per-connection-size=50
spring.datasource.druid.max-open-prepared-statements=20
spring.datasource.druid.validation-query=select 1
spring.datasource.druid.validation-query-timeout=60000
spring.datasource.druid.test-on-borrow=false
spring.datasource.druid.test-on-return=false
spring.datasource.druid.test-while-idle=true

## 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.druid.time-between-eviction-runs-millis=2000

## 配置一个连接在池中最小和最大生存的时间,单位是毫秒
spring.datasource.druid.min-evictable-idle-time-millis=300000
spring.datasource.druid.max-evictable-idle-time-millis=600000

#####druid监控配置
## WebStatFilter配置,说明请参考Druid Wiki,配置_配置WebStatFilter
#是否启用StatFilter默认值true
spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*

#session统计功能
#spring.datasource.druid.web-stat-filter.session-stat-enable=true
#最大session数
#spring.datasource.druid.web-stat-filter.session-stat-max-count=100000
#你可以配置principalSessionName,使得druid能够知道当前的session的用户是谁
#spring.datasource.druid.web-stat-filter.principal-session-name=admin
#你可以配置principalSessionName,使得druid能够知道当前的cookie的用户是谁
#spring.datasource.druid.web-stat-filter.principal-cookie-name=admin

#置profileEnable能够监控单个url调用的sql列表。
spring.datasource.druid.web-stat-filter.profile-enable=true

## StatViewServlet配置,说明请参考Druid Wiki,配置_StatViewServlet配置
spring.datasource.druid.stat-view-servlet.enabled=true
spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
spring.datasource.druid.stat-view-servlet.reset-enable=true
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin

## IP黑白名单配置,deny优先于allow,如果在deny列表中,就算在allow列表中,也会被拒绝。
## 如果allow没有配置或者为空,则允许所有访问
#spring.datasource.druid.stat-view-servlet.allow=127.0.0.1
#spring.datasource.druid.stat-view-servlet.deny=192.168.10.1

## Spring监控配置,说明请参考Druid Github Wiki,配置_Druid和Spring关联监控配置
# Spring监控AOP切入点,如x.y.z.service.*,配置多个英文逗号分隔
#spring.datasource.druid.aop-patterns= org.lsh.dubhe.service.*

#配置wall filter
spring.datasource.druid.filter.wall.enabled=true
spring.datasource.druid.filter.wall.db-type=mysql
spring.datasource.druid.filter.wall.config.alter-table-allow=false
spring.datasource.druid.filter.wall.config.truncate-allow=false
spring.datasource.druid.filter.wall.config.drop-table-allow=false

#是否允许非以上基本语句的其他语句,缺省关闭,通过这个选项就能够屏蔽DDL。
spring.datasource.druid.filter.wall.config.none-base-statement-allow=false
#检查UPDATE语句是否无where条件,这是有风险的,但不是SQL注入类型的风险
spring.datasource.druid.filter.wall.config.update-where-none-check=true
#SELECT ... INTO OUTFILE 是否允许,这个是mysql注入攻击的常见手段,缺省是禁止的
spring.datasource.druid.filter.wall.config.select-into-outfile-allow=false
#是否允许调用Connection.getMetadata方法,这个方法调用会暴露数据库的表信息
spring.datasource.druid.filter.wall.config.metadata-allow=true
#对被认为是攻击的SQL进行LOG.error输出
spring.datasource.druid.filter.wall.log-violation=true
#对被认为是攻击的SQL抛出SQLExcepton
spring.datasource.druid.filter.wall.throw-exception=true

Start spring boot, and then enter http://localhost:8080/druid/index.html to access
insert image description here
insert image description here
Method 2: Introduce druid dependencies

<dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid</artifactId>
     <version>1.1.12</version>
</dependency>

Add the following configuration to application.properties

#数据库配置
# 驱动配置信息
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis?useSSL=false&characterEncoding=utf8&serverTimezone=GMT
spring.datasource.username=hqh
spring.datasource.password=Mysql123
spring.datasource.driverClassName=com.mysql.cj.jdbc.Driver

# 连接池的配置信息
# 初始化大小,最小,最大
spring.datasource.initialSize=3
spring.datasource.minIdle=5
spring.datasource.maxActive=20

# 配置获取连接等待超时的时间
spring.datasource.maxWait=30000
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
spring.datasource.timeBetweenEvictionRunsMillis=60000

# 配置一个连接在池中最小生存的时间,单位是毫秒
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1 FROM DUAL
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false

# 打开PSCache,并且指定每个连接上PSCache的大小
spring.datasource.poolPreparedStatements=true
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
spring.datasource.filters=stat,wall
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=10000

Create a Druid configuration class

package com.flashsale.config;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

@Configuration
public class DruidConfiguration {
    
    

	private static final Logger logger = LoggerFactory.getLogger(DruidConfiguration.class);

	private static final String DB_PREFIX = "spring.datasource";

	@Bean
	public ServletRegistrationBean<StatViewServlet> druidServlet() {
    
    
		logger.info("init Druid Servlet Configuration ");
		ServletRegistrationBean<StatViewServlet> servletRegistrationBean = new ServletRegistrationBean<StatViewServlet>(
				new StatViewServlet(), "/druid/*");
		// IP白名单(deny优先于allow,如果在deny列表中,就算在allow列表中,也会被拒绝。如果allow没有配置或者为空,则允许所有访问)
//		servletRegistrationBean.addInitParameter("allow", "*");

		// IP黑名单(共同存在时,deny优先于allow)
//		servletRegistrationBean.addInitParameter("deny", "192.168.1.100");

		// 控制台管理用户
		servletRegistrationBean.addInitParameter("loginUsername", "admin");
		servletRegistrationBean.addInitParameter("loginPassword", "admin");

		// 是否能够重置数据 禁用HTML页面上的“Reset All”功能
		servletRegistrationBean.addInitParameter("resetEnable", "false");
		return servletRegistrationBean;
	}

	@Bean
	public FilterRegistrationBean<WebStatFilter> filterRegistrationBean() {
    
    
		FilterRegistrationBean<WebStatFilter> filterRegistrationBean = new FilterRegistrationBean<WebStatFilter>(new WebStatFilter());
		filterRegistrationBean.addUrlPatterns("/*");
		filterRegistrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.png,*.css,*.ico, /druid/*");
		return filterRegistrationBean;
	}
	
	// 声明其为Bean实例(如果没配置initMethod和destroyMethod,在监控数据源处会报错(*) property for user to setup)
	@Bean(destroyMethod="close", initMethod="init")
	@ConfigurationProperties(prefix = DB_PREFIX)
	public DataSource dataSource() {
    
    
		return new DruidDataSource();
	}
}

Start spring boot, then enter http://localhost:8080/druid/index.html to access
insert image description here

Guess you like

Origin blog.csdn.net/q283614346/article/details/90727612