引入依赖
<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;
}
}
复制代码