1、pom.xml配置文件引入依赖
<!-- 引入druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.8</version>
</dependency>
2、application.properties配置文件配置相关的数据源连接
#数据源
spring.datasource.url=jdbc:mysql://localhost:3306/zhao?serverTimezone=Asia/Shanghai&useSSL=false&characterEncoding=utf8
spring.datasource.username=root
spring.datasource.password=root
spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver
spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=20
spring.datasource.maxWait=60000
spring.datasource.timeBetweenEvictionRunsMillis=60000
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=select 1 from dual
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
spring.datasource.poolPreparedStatements=true
# 配置监控统计拦截的Filters,去掉监控界面的sql无法统计,wall用于防火墙
spring.datasource.filters=stat,wall,log4j
spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
spring.datasource.userGlobalDataSourceStat=true
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3、创建配置类DruidConfig
@Configuration
public class DruidConfig {
@ConfigurationProperties(prefix = "spring.datasource")
@Bean
public DataSource druid(){
return new DruidDataSource();
}
/**
* 配置Druid监控
* 配置一个管理后台的Servlet
* @return
*/
@Bean
public ServletRegistrationBean statViewServlet(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
Map<String,String> initParams = new HashMap<>();
//登录后台的用户名密码
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123456");
// 默认访问所有
initParams.put("allow","/");
// 拒绝访问哪些
// initParams.put("deny","");
bean.setInitParameters(initParams);
return bean;
}
/**
* 控制一个web监控的filter
* @return
*/
@Bean
public FilterRegistrationBean webStatFilter(){
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
Map<String,String> intiParams = new HashMap<>();
intiParams.put("exclusions","*.js,*.css,/druid/*");
bean.setInitParameters(intiParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
4、重启项目,输入http://localhost:8080/druid进入登录页面,输入配置好的用户名和密码,即可进入
5、登录进去之后,即可查看,数据源监控
到此就可以使用了。