1、引入Druid数据源依赖
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.21</version>
</dependency>
2、修改SpringBoot配置文件
spring:
datasource:
username: root
password: root
url: jdbc:mysql://127.0.0.1:3306/test
driver-class-name: com.mysql.cj.jdbc.Driver
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
poolPreparedStatements: true
## 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
filters: stat,wall
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
3、编写数据源配置类
/**
* Druid数据配置类
**/
@Configuration
public class MyDruidConfiguration {
/**
* 配置自定义数据源
* @return
*/
@Bean
// 导入配置文件的配置
@ConfigurationProperties(prefix = "spring.datasource")
public DataSource myDruidDataSource(){
return new DruidDataSource();
}
/**
* 配置Druid的监控管理后台
* @return
*/
@Bean
public ServletRegistrationBean druidServletRegistrationBean(){
ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
Map<String, String> initParams = new HashMap<>();
initParams.put("loginUsername", "admin");
initParams.put("loginPassword", "admin");
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 initParams = new HashMap();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
}
4、测试
访问:http://localhost:8080/druid/,输入配置的用户名和密码即可登录Druid数据源管理后台。