Druid数据库监控
一、简介
Druid是阿里开源的一个JDBC应用组件, 其包括三部分:
-
DruidDriver: 代理Driver,能够提供基于Filter-Chain模式的插件体系。
-
DruidDataSource: 高效可管理的数据库连接池。
-
SQLParser: 实用的SQL语法分析
通过Druid连接池中间件, 我们可以实现:
-
可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。
-
替换传统的DBCP和C3P0连接池中间件。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。
-
数据库密码加密。直接把数据库密码写在配置文件中,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。
-
SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-Logging、Log4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。
-
扩展JDBC,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter-Chain机制,很方便编写JDBC层的扩展插件
<p>更多详细信息参考官方文档:<a href="https://github.com/alibaba/druid/wiki">https://github.com/alibaba/druid/wiki</a></p> </li>
Druid Spring Boot Starter 是阿里官方提供的 Spring Boot 插件,用于帮助在Spring Boot项目中轻松集成Druid数据库连接池和监控。
更多资料参考:
Druid: https://github.com/alibaba/druid
Druid Spring Starter: https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter
二、搭建demo
(1)创建项目
创建spring boot项目
(2)依赖
- <?xml version="1.0" encoding="UTF-8"?>
- <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
- xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 https://maven.apache.org/xsd/maven-4.0.0.xsd">
- <modelVersion>4.0.0</modelVersion>
- <parent>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-starter-parent</artifactId>
- <version>2.1.7.RELEASE</version>
- <relativePath/> <!-- lookup parent from repository -->
- </parent>
- <groupId>com.zzq</groupId>
- <artifactId>sping-data-monitor</artifactId>
- <version>0.0.1-SNAPSHOT</version>
- <name>sping-data-monitor</name>
- <description>Demo project for Spring Boot</description>
-
- <properties>
- <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
- <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
- <java.version>1.8</java.version>
- </properties>
-
- <dependencies>
- <dependency>
- <groupId>com.alibaba</groupId>
- <artifactId>druid</artifactId>
- <version>1.1.10</version>
- </dependency>
- <!--修改MySQL驱动版本-->
- <dependency>
- <groupId>mysql</groupId>
- <artifactId>mysql-connector-java</artifactId>
- <version>5.1.47</version>
- <scope>runtime</scope>
- </dependency>
- </dependencies>
- <build>
- <plugins>
- <plugin>
- <groupId>org.springframework.boot</groupId>
- <artifactId>spring-boot-maven-plugin</artifactId>
- </plugin>
- </plugins>
- </build>
-
- </project>
(3)application.properties配置
- application:
- name: sping-data-monitor # 暴露微服务名称
- #数据库配置
- # 驱动配置信息
- spring.datasource.type=com.alibaba.druid.pool.DruidDataSource
- spring.datasource.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=false&zeroDateTimeBehavior=convertToNull
- spring.datasource.username=root
- spring.datasource.password=root
- spring.datasource.driver-class-name=com.mysql.jdbc.Driver
-
- # 连接池的配置信息
- # 初始化大小,最小,最大
- spring.datasource.initialSize=3
- spring.datasource.minIdle=5
- spring.datasource.maxActive=20
-
- # 配置获取连接等待超时的时间
- spring.datasource.maxWait=30000
- # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
- 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
-
- # 打开PSCache,并且指定每个连接上PSCache的大小
- spring.datasource.poolPreparedStatements=true
- spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
- # 配置监控统计拦截的filters,去掉后监控界面sql无法统计,'wall'用于防火墙
- spring.datasource.filters=stat,wall
- # 通过connectProperties属性来打开mergeSql功能;慢SQL记录
- spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=10000
-
(4)DruidDBConfig
- package com.zzq.config;
-
- import com.alibaba.druid.pool.DruidDataSource;
- import org.slf4j.Logger;
- import org.slf4j.LoggerFactory;
- import org.springframework.beans.factory.annotation.Value;
- import org.springframework.context.annotation.Bean;
- import org.springframework.context.annotation.Configuration;
- import org.springframework.context.annotation.Primary;
-
- import javax.sql.DataSource;
- import java.sql.SQLException;
-
-
- @Configuration
- public class DruidDBConfig {
-
- private Logger logger = LoggerFactory.getLogger(DruidDBConfig.class);
-
- @Value("${spring.datasource.url}")
- private String dbUrl;
-
- @Value("${spring.datasource.username}")
- private String username;
-
- @Value("${spring.datasource.password}")
- private String password;
-
- @Value("${spring.datasource.driver-class-name}")
- private String driverClassName;
-
- @Value("${spring.datasource.initialSize}")
- private int initialSize;
-
- @Value("${spring.datasource.minIdle}")
- private int minIdle;
-
- @Value("${spring.datasource.maxActive}")
- private int maxActive;
-
- @Value("${spring.datasource.maxWait}")
- private int maxWait;
-
- @Value("${spring.datasource.timeBetweenEvictionRunsMillis}")
- private int timeBetweenEvictionRunsMillis;
-
- @Value("${spring.datasource.minEvictableIdleTimeMillis}")
- private int minEvictableIdleTimeMillis;
-
- @Value("${spring.datasource.validationQuery}")
- private String validationQuery;
-
- @Value("${spring.datasource.testWhileIdle}")
- private boolean testWhileIdle;
-
- @Value("${spring.datasource.testOnBorrow}")
- private boolean testOnBorrow;
-
- @Value("${spring.datasource.testOnReturn}")
- private boolean testOnReturn;
-
- @Value("${spring.datasource.poolPreparedStatements}")
- private boolean poolPreparedStatements;
-
- @Value("${spring.datasource.maxPoolPreparedStatementPerConnectionSize}")
- private int maxPoolPreparedStatementPerConnectionSize;
-
- @Value("${spring.datasource.filters}")
- private String filters;
-
- @Value("{spring.datasource.connectionProperties}")
- private String connectionProperties;
-
- /**
- * @Bean 声明,DataSource 对象为 Spring 容器所管理;
- * @Primary 表示这里定义的DataSource将覆盖其他来源的DataSource。
- * StatFilter,用于统计监控信息。StatFilter的别名是stat。
- * 统计SQL信息,合并统计。mergeStat是的MergeStatFilter缩写。
- * 通过 DataSource 的属性<property name="filters" value="mergeStat" /> 或者
- * connectProperties属性来打开mergeSql功能 <property name="connectionProperties" value="druid.stat.mergeSql=true" />
- * StatFilter属性slowSqlMillis用来配置SQL慢的标准
- *
- * @return
- */
- @Bean
- @Primary
- public DataSource dataSource() {
- DruidDataSource datasource = new DruidDataSource();
- datasource.setUrl(dbUrl);
- datasource.setDriverClassName(driverClassName);
- datasource.setUsername(username);
- datasource.setPassword(password);
-
- //configuration
- datasource.setInitialSize(initialSize);
- datasource.setMinIdle(minIdle);
- datasource.setMaxActive(maxActive);
- datasource.setMaxWait(maxWait);
- datasource.setTimeBetweenEvictionRunsMillis(timeBetweenEvictionRunsMillis);
- datasource.setMinEvictableIdleTimeMillis(minEvictableIdleTimeMillis);
- datasource.setValidationQuery(validationQuery);
- datasource.setTestWhileIdle(testWhileIdle);
- datasource.setTestOnBorrow(testOnBorrow);
- datasource.setTestOnReturn(testOnReturn);
- datasource.setPoolPreparedStatements(poolPreparedStatements);
- datasource.setMaxPoolPreparedStatementPerConnectionSize(maxPoolPreparedStatementPerConnectionSize);
- try {
- /**
- * 设置StatFilter,用于统计监控信息。
- * StatFilter的别名是stat
- *
- */
- datasource.setFilters(filters);
- } catch (SQLException e) {
- logger.error("druid configuration initialization filter : {0}",e);
- }
- datasource.setConnectionProperties(connectionProperties);
-
- return datasource;
- }
-
- }
(5)DruidStatFilter
- package com.zzq.filter;
-
- import com.alibaba.druid.support.http.WebStatFilter;
-
- import javax.servlet.annotation.WebFilter;
- import javax.servlet.annotation.WebInitParam;
-
- /**
- * WebStatFilter用于采集web-jdbc关联监控的数据。
- * 属性filterName声明过滤器的名称,可选
- * 属性urlPatterns指定要过滤 的URL模式,也可使用属性value来声明.(指定要过滤的URL模式是必选属性)
- */
-
- @WebFilter(
- urlPatterns = "/sping-data-monitor/*",
- initParams = {
- @WebInitParam(name = "exclusions",value = "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*")
- }
- )
- public class DruidStatFilter extends WebStatFilter {
- }
(6)DruidStatViewServlet
- package com.zzq.servlet;
-
- import com.alibaba.druid.support.http.StatViewServlet;
-
- import javax.servlet.annotation.WebInitParam;
- import javax.servlet.annotation.WebServlet;
-
- /**
- * StatViewServlet用于展示Druid的统计信息。
- * 提供监控信息展示的html页面
- * 提供监控信息的JSON API
- *
- * 内置监控页面的首页是/druid/index.html
- *
- */
-
- /**
- * @Webservlet
- * 有两个属性可以用来表示Servlet的访问路径,分别是value和urlPatterns。value和urlPatterns都是数组形式,
- * 表示我们可以把一个Servlet映射到多个访问路径,但是value和urlPatterns不能同时使用。
- *
- */
- @WebServlet(
- urlPatterns = {"/druid/*"},//#监控地址,默认 /druid/*
- initParams = {
- @WebInitParam(name = "loginUsername", value = "admin"),//#登录用户名
- @WebInitParam(name = "loginPassword", value = "admin"),//#登录密码
- @WebInitParam(name = "resetEnable", value = "false"),
- // @WebInitParam(name = "allow", value = "127.0.0.1") #IP 白名单
- }
- )
- public class DruidStatViewServlet extends StatViewServlet {
- }
(7)启动类
- package com.zzq;
-
- import org.springframework.boot.SpringApplication;
- import org.springframework.boot.autoconfigure.SpringBootApplication;
- import org.springframework.boot.web.servlet.ServletComponentScan;
-
- @SpringBootApplication
- @ServletComponentScan(basePackages = {"com.zzq.**.servlet"})
- public class SpingDataMonitorApplication {
-
- public static void main(String[] args) {
- SpringApplication.run(SpingDataMonitorApplication.class, args);
- }
-
- }
(8)效果
http://localhost:8080/druid/login.html
用户名/密码 admin/admin