<dependency> <groupId>com.alibaba</groupId> <artifactId>druid-spring-boot-starter</artifactId> <version>1.1.10</version> </dependency>
1.1.10是版本号,可以自行进行修改 然后就是在application.yml或者是application.properties文件进行修改配置:
spring: datasource: username: root password: root url: jdbc:mysql://192.168.43.197:3306/jdbc driver-class-name: com.mysql.cj.jdbc.Driver # 指定数据源的类型位druid type: com.alibaba.druid.pool.DruidDataSource 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,log4j maxPoolPreparedStatementPerConnectionSize: 20 useGlobalDataSourceStat: true connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500 # # initialization-mode: always # schema: # - classpath:department.sql
然后就是定制我们的后台的监控:
@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","localhost");//默认就是允许所有访问 initParams.put("deny","192.168.79.1"); bean.setInitParameters(initParams); return bean; } @Bean public FilterRegistrationBean webStatFilter(){ FilterRegistrationBean bean = new FilterRegistrationBean(); bean.setFilter(new WebStatFilter()); Map<String,String> initParams = new HashMap<>(); initParams.put("exclusions","*.js,*.css,/druid/*"); bean.setInitParameters(initParams); bean.setUrlPatterns(Arrays.asList("/*")); return bean; }
然后在我们的地址栏输入我们的ip:端口号就可以进行访问druid的后台监控中心 后台的所有的监控都可以这里进行查看 在测试类里面进行查看我们的druid的信息配置: 测试类;
package com.jdbc.demo; import org.junit.Test; import org.junit.runner.RunWith; import org.springframework.beans.factory.annotation.Autowired; import org.springframework.boot.test.context.SpringBootTest; import org.springframework.test.context.junit4.SpringRunner; import javax.sql.DataSource; import java.sql.Connection; import java.sql.SQLException; @RunWith(SpringRunner.class) @SpringBootTest public class DemoApplicationTests { @Autowired DataSource dataSource; @Test public void contextLoads() throws SQLException { System.out.println(dataSource.getClass()); Connection connection = dataSource.getConnection(); System.out.println(connection); connection.close(); } }
以debug的方式运行,就可以看到我们的配置是否生效: 我们发送一个query的请求: 然后在我们的后台监控的网址下: 就可以看见我们的sql的监控: