SpringBoot2.0整合Druid连接池,作一个记录。
- 在pom.xml引入druid的依赖
<!-- 整合Druid数据源 -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.18</version>
</dependency>
- 设置配置文件属性,这里以application.yml文件为例
spring:
datasource:
username: root
password: 123456
url: jdbc:mysql://192.168.1.73:3306/springboot-jdbc
driver-class-name: com.mysql.cj.jdbc.Driver
type: com.alibaba.druid.pool.DruidDataSource
# 数据源其他配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
poolPreparedStatements: true
# 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- 由于默认的Druid的其他配置不会生效,所以我们要写一个Druid的配置类,使设置的数据源其他配置生效
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
DruidDataSource druidDataSource = new DruidDataSource();
return druidDataSource;
}
......
//添加Druid的管理后台的Servlet和Web监控的Filter
}
- 配置Druid管理后台的Servlet
`` @Bean
public ServletRegistrationBean StatViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> map = new HashMap<>();
//配置StatViewServlet父类ResourceServlet属性
map.put("loginUsername","admin");
map.put("loginPassword","123456");
map.put("allow",""); //允许访问
bean.setInitParameters(map); //设置属性进注册servlet
return bean;
}
- 配置Druid的web监控的Filter
@Bean
public FilterRegistrationBean WebStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String > map = new HashMap<>();
map.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(map);
//设置拦截请求,这里设置拦截所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
- 配置完成,启动应用,访问http://localhost:8080/druid/ 进入Druid监控的登陆页面,用户名:
admin
,密码:123456
- 访问自定义的请求
localhost:8080/query
查询数据库数据,可以通过Druid的监控后台的SQL监控查看到执行的sql
SpringBoot2.0整合Druid连接池完成!!!