引入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.19</version>
</dependency>
复制代码
在spring配置文件application.yml中新增如下配置
spring:
datasource:
url: jdbc:mysql://localhost:3306/***?useUnicode=true&characterEncoding=utf8
username: root
password: root
driver-class-name: com.mysql.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 最小连接池数量
minIdle: 3
# 最大连接池数量
maxActive: 20
# 获取连接时最大等待时间,单位毫秒
maxWait: 60000
# 初始化时建立物理连接的个数
initialSize: 2
# 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
timeBetweenEvictionRunsMillis: 60000
# 配置一个连接在池中最小生存的时间,单位是毫秒
minEvictableIdleTimeMillis: 30000
# 检测连接是否有效
validationQuery: select 'x'
# 申请连接的时候检测,建议配置为true,不影响性能,并且保证安全性
testWhileIdle: true
# 获取连接时执行检测,影响性能,建议关闭
testOnBorrow: false
# 归还连接时执行检测,影响性能,建议关闭
testOnReturn: false
# 打开PSCache,并且指定每个连接上PSCache的大小,PSCache对支持游标的数据库性能提升巨大,oracle建议开启,mysql建议关闭
poolPreparedStatements: false
maxPoolPreparedStatementPerConnectionSize: 20
# 配置插件 stat:监控统计 wall:防御sql注入 log4j:日志
filters: stat,wall,log4j
# 通过connectProperties属性来打开mergeSql功能;慢SQL记录
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
复制代码
新建druid配置文件,代码如下
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
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 org.springframework.context.annotation.Primary;
@Configuration
public class DruidConfig {
@Primary
@Bean(destroyMethod = "close")
@ConfigurationProperties(prefix = "spring.datasource")
public DruidDataSource dataSource(){
return new DruidDataSource();
}
@Bean
public FilterRegistrationBean statFilter(){
FilterRegistrationBean filter = new FilterRegistrationBean(new WebStatFilter());
filter.addUrlPatterns("/*");
filter.addInitParameter("exclusions", "*.js,*.gif,*.png,*.jpg,*.css,*.ico,/druid/*");
return filter;
}
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean servlet = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
servlet.addInitParameter("allow", "127.0.0.1");
servlet.addInitParameter("deny","192.168.1.4");
servlet.addInitParameter("loginUsername","root");
servlet.addInitParameter("loginPassword","root");
servlet.addInitParameter("resetEnable","true");
return servlet;
}
}
复制代码