springboot整合Druid连接池
Druid
是一个阿里开源的连接池组件
加⼊了日志监控,不需要额外的界面开发
1.导入依赖
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.1.21</version>
</dependenc>
2.编写配置文件:application.yaml
server:
port: 8080
spring:
application:
name: p6spyDemo
datasource:
driver-class-name: com.mysql.cj.jdbc.Driver
username: root
password: root
url: jdbc:mysql://localhost:3306/demo?useUnicode=true&characterEncoding=UTF-8
type: com.alibaba.druid.pool.DruidDataSource
#druid 数据源专有配置
initialSize: 5
minIdle: 5
maxActive: 20
maxWait: 60000
timeBetweenEvictionRunsMillis: 60000
minEvictableIdleTimeMillis: 300000
validationQuery: SELECT 1 FROM DUAL
testWhileIdle: true
testOnBorrow: false
testOnReturn: false
# 打开PSCache
poolPreparedStatements: true
#配置监控统计拦截的filters,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果运行时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority
#则导入 log4j 依赖即可,Maven 地址: https://mvnrepository.com/artifact/log4j/log4j
filters: stat,wall,log4j,config
#指定每个连接上PSCache的大小
maxPoolPreparedStatementPerConnectionSize: 20
#合并多个DruidDataSource的监控数据
useGlobalDataSourceStat: true
#通过connectProperties属性来打开mergeSql功能;慢SQL记录
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
3.编写配置类:
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druidDataSource(){
return new DruidDataSource();
}
//因为Springboot内置了servlet容器,所以没有web.xml,替代方法就是将ServletRegistrationBean注册进去
//加入后台监控
@Bean //这里其实就相当于servlet的web.xml
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean<StatViewServlet> bean =
new ServletRegistrationBean<StatViewServlet>(new StatViewServlet(),"/druid/*");
//后台需要有人登录,进行配置
//bean.addUrlMappings(); 这个可以添加映射,我们在构造里已经写了
//设置一些初始化参数
Map<String,String> initParas = new HashMap<String,String>();
initParas.put("loginUsername","admin");//它这个账户密码是固定的
initParas.put("loginPassword","123456");
//允许谁能防伪
initParas.put("allow","");//这个值为空或没有就允许所有人访问,ip白名单
//initParas.put("allow","localhost");//只允许本机访问,多个ip用逗号,隔开
//initParas.put("deny","");//ip黑名单,拒绝谁访问 deny和allow同时存在优先deny
initParas.put("resetEnable","false");//禁用HTML页面的Reset按钮
bean.setInitParameters(initParas);
return bean;
}
//再配置一个过滤器,Servlet按上面的方式注册Filter也只能这样
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
//可以设置也可以获取,设置一个阿里巴巴的过滤器
bean.setFilter(new WebStatFilter());
bean.addUrlPatterns("/*");
//可以过滤和排除哪些东西
Map<String,String> initParams = new HashMap<String,String>();
//把不需要监控的过滤掉,这些不进行统计
initParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
return bean;
}
4.启动项目后,访问页面http://127.0.0.1:8001/druid/sql.html,就可以访问监控页面了。