Druid整合以及开启监控
2020-08-27 10:59:28 37
Druid是Java语言中最好的数据库连接池。Druid能够提供强大的监控和扩展功能。
1,首先导入maven依赖:
<!-- druid -->
<dependency>
<groupId>com.alibaba</groupId>
<artifactId>druid</artifactId>
<version>1.1.14</version>
</dependency>
2,便写@Configuration配置交给spring管理
/**druid的配置类
* @author sy
* @date 2019/3/14 17:35
*/
@Configuration
public class DruidConfig {
@Value("${spring.druid.slowSqlMillis}")
private Long slowSqlMillis;
//会扫描application.properties文件的以spring.druid开头的数据注入
@ConfigurationProperties(prefix = "spring.druid")
@Bean(initMethod = "init",destroyMethod = "close") //跟着spring一块启动,一块关闭
public DruidDataSource dataSource(){
DruidDataSource dataSource = new DruidDataSource();
dataSource.setProxyFilters(Lists.newArrayList(statFilter()));//Lists是guava包
return dataSource;
}
//alibaba的监听器,打印慢sql
@Bean
public Filter statFilter(){
StatFilter filter = new StatFilter();
filter.setSlowSqlMillis(slowSqlMillis);
filter.setLogSlowSql(true);
filter.setMergeSql(true);
return filter;
}
@Bean
public ServletRegistrationBean servletRegistrationBean(){
return new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
}
}
3,编写application.properties文件
server.port=8010
#druid 阿里巴巴下的一个开源连接池:功能强大,可以监控,稳定。
spring.druid.driverClassName=com.mysql.cj.jdbc.Driver
spring.druid.url=jdbc:mysql://localhost:3306/app?characterEncoding=UTF-8&serverTimezone=Asia/Shanghai&useSSL=false
spring.druid.username=root
spring.druid.password=123456
#最大连接数
spring.druid.maxActive=30
#最小连接数
spring.druid.minIdle=5
#获取连接的最大等待时间
spring.druid.maxWait=10000
#解决mysql8小时的问题
spring.druid.validationQuery=SELECT 'x'
#指定超过多少秒为慢sql
spring.druid.slowSqlMillis=3
启动项目访问:http://localhost:8010/druid/datasource.html,就可以直接对sql进行监控啦。
睿江云官网链接:www.eflycloud.com