Druid 是阿里巴巴开源平台上一个数据库连接池实现,结合了 C3P0、DBCP 等 DB 池的优点,同时加入了日志监控。
Druid 可以很好的监控 DB 池连接和 SQL 的执行情况,天生就是针对监控而生的 DB 连接池。
一、导入依赖com.alibaba druid1.1.21
前提是已经导入了
二、配置文件log4j log4j1.2.17 org.springframework.boot spring-boot-starter-jdbcorg.springframework.boot spring-boot-starter-thymeleaforg.springframework.boot spring-boot-starter-webmysql mysql-connector-javaruntime org.springframework.boot spring-boot-starter-testtest
因为springboot默认不是bruid数据源,所以需要配置为bruid
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
#SpringBoot默认是不注入这些的,需要自己绑定
#druid数据源专有配置
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,stat:监控统计、log4j:日志记录、wall:防御sql注入
#如果允许报错,java.lang.ClassNotFoundException: org.apache.Log4j.Properity
#则导入log4j 依赖就行
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
三、配置类
自定义一个配置类,起名为DruidConfig。标上@Configuration注解,说明是一个配置类
@ConfigurationProperties(prefix = "spring.datasource")//与配置文件绑定
@Bean//交给springboot处理
public DataSource bruidDataSource(){
return new DruidDataSource();//返回Druid数据源
}
//后台监控功能
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean<>(new StatViewServlet(), "/druid/*");//配置访问路径
HashMap a = new HashMap<>();
//增加配置
a.put("loginUsername","admin"); //loginUsername 与 loginPassword 是固定的 不能改变
a.put("loginPassword","123456");
//允许谁可以访问
a.put("allow","");
//后台需要有人登录,账号密码配置
bean.setInitParameters(a); //设置初始化参数
return bean;
}
四、运行
启动springboot,运行在配置类中的访问路径,也就是localhost:8080/druid就会跳转到一个写好的 可以直接使用的界面
然后输入你在配置类中输入的用户名与密码就进入了首页,就可以实现栏下的功能



