方法一:
- 导入jar
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.0.26</version>
</dependency>
- yml配置
spring:
datasource:
type: com.alibaba.druid.pool.DruidDataSource
driver-class-name: com.mysql.jdbc.Driver
username: root
password: root
url: jdbc:mysql:///test?useSSL=false
- 自定义DataSource
@ConfigurationProperties(prefix = “spring.datasource”)
@Bean
public DataSource dataSource() {
DruidDataSource dataSource = new DruidDataSource();
return dataSource;
}
方法二:
- 导入jar
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid-spring-boot-starter</artifactId>
<version>1.2.8</version>
</dependency>
- yml配置
spring:
datasource:
druid:
max-pool-prepared-statement-per-connection-size: 20
use-global-data-source-stat: true
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
username: root
password: root
url: jdbc:mysql:///test?useSSL=false
driver-class-name: com.mysql.jdbc.Driver
与方法一的区别是 不需要自己定义DataSource ,如果需要使用到druid的控制台功能,则需要如下操作:
- 自动配置bean
@Bean
public ServletRegistrationBean druidServletRegistrationBean(){
ServletRegistrationBean<Servlet> servletRegistrationBean = new ServletRegistrationBean<>(new StatViewServlet(),"/druid/*");
Map<String,String> initParams = new HashMap<>();
initParams.put("loginUsername","admin");
initParams.put("loginPassword","123");
//后台允许谁可以访问
//initParams.put("allow", "localhost"):表示只有本机可以访问
//initParams.put("allow", ""):为空或者为null时,表示允许所有访问
initParams.put("allow","");
//deny:Druid 后台拒绝谁访问
//initParams.put("msb", "192.168.1.20");表示禁止此ip访问
servletRegistrationBean.setInitParameters(initParams);
return servletRegistrationBean;
}
//配置Druid web监控的filter
//WebStatFilter:用于配置Web和Druid数据源之间的管理关联监控统计
@Bean
public FilterRegistrationBean webStatFilter() {
FilterRegistrationBean bean = new FilterRegistrationBean();
bean.setFilter(new WebStatFilter());
//exclusions:设置哪些请求进行过滤排除掉,从而不进行统计
Map<String, String> initParams = new HashMap<>();
initParams.put("exclusions", "*.js,*.css,/druid/*");
bean.setInitParameters(initParams);
//"/*" 表示过滤所有请求
bean.setUrlPatterns(Arrays.asList("/*"));
return bean;
}
- yml配置
spring:
datasource:
druid:
filters: stat,wall,log4j
max-pool-prepared-statement-per-connection-size: 20
use-global-data-source-stat: true
connection-properties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500
- 控制台展示
- 如果控制台展示未能监控到sql记录,那应该是yml配置未能生效。