SpringBoot集成Druid监控数据源配置,访问监控页面

Druid 介绍

Druid首先是一个数据库连接池。Druid是目前最好的数据库连接池,在功能、性能、扩展性方面,都超过其他数据库连接池,包括DBCP、C3P0、BoneCP、Proxool、JBoss DataSource。Druid已经在阿里巴巴部署了超过600个应用,经过一年多生产环境大规模部署的严苛考验。Druid是阿里巴巴开发的号称为监控而生的数据库连接池!

Druid是一个JDBC组件,它包括三个部分:

基于Filter-Chain模式的插件体系。

DruidDataSource 高效可管理的数据库连接池。

SQLParser

Druid 整个项⽬由数据库连接池、插件框架和 SQL 解析器组成,该项⽬主要是为了扩展 JDBC 的⼀些限制,可以让程序员实现⼀些特殊的需求,⽐如向密钥服务请求凭证、统计SQL 信息、SQL 性能收集、SQL 注⼊检查、SQL 翻译等,程序员可以通过定制来实现⾃⼰需要的功能。

Druid 可以做什么

替换其他 Java 连接池,Druid 提供了⼀个⾼效、功能强⼤、可扩展性好的数据库连接池。
可以监控数据库访问性能,Druid 内置提供了⼀个功能强⼤的 StatFilter 插件,能够详细统计 SQL 的执
⾏性能,这对于线上分析数据库访问性能有很⼤帮助。
数据库密码加密。直接把数据库密码写在配置⽂件中,这是不好的⾏为,容易导致安全问题,
DruidDruiver 和 DruidDataSource 都⽀持 PasswordCallback。
SQL 执⾏⽇志,Druid 提供了不同的 LogFilter,能够⽀持 Common-Logging、Log4j 和 JdkLog,可以
按需要选择相应的 LogFilter,监控应⽤的数据库访问情况。
扩展 JDBC,如果你要对 JDBC 层有编程的需求,可以通过 Druid 提供的 Filter 机制,很⽅便编写
JDBC 层的扩展插件。

Spring Boot 集成 Druid

⾮常令⼈⾼兴的是,阿⾥为 Druid 也提供了 Spring Boot Starter 的⽀持。官⽹这样解释:Druid Spring Boot
Starter ⽤于帮助你在 Spring Boot 项⽬中轻松集成 Druid 数据库连接池和监控。
Druid Spring Boot Starter 主要做了哪些事情呢?其实这个组件包很简单,主要提供了很多⾃动化的配置,按照 Spring Boot 的理念对很多内容进⾏了预配置,让我们在使⽤的时候更加的简单和⽅便。

下面有一个小案例,使用druid作为配置源,并访问监控页面,整体结构如下
在这里插入图片描述

由于druid的监控页面是使用的servlet,所以必须有servlet,而且要开启扫描否则无法访问druid后台监控页面。

以下是pom:

<?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.3.1.RELEASE</version>
        <relativePath/> <!-- lookup parent from repository -->
    </parent>
    <groupId>com.example</groupId>
    <artifactId>druid</artifactId>
    <version>0.0.1-SNAPSHOT</version>
    <name>druid</name>
    <description>Demo project for Spring Boot</description>

    <properties>
        <java.version>1.8</java.version>
    </properties>

    <dependencies>
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter</artifactId>
        </dependency>

        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-web</artifactId>
        </dependency>

        <!--配置druid数据源-->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.10</version>
        </dependency>

        <dependency>
            <groupId>org.mybatis.spring.boot</groupId>
            <artifactId>mybatis-spring-boot-starter</artifactId>
            <version>1.3.2</version>
        </dependency>

        <dependency>
            <groupId>mysql</groupId>
            <artifactId>mysql-connector-java</artifactId>
            <version>5.1.47</version>
        </dependency>

        <!--<dependency>
            <groupId>org.springframework.data</groupId>
            <artifactId>spring-data-jpa</artifactId>
            <version>2.3.0.RELEASE</version>
        </dependency>
-->
        <dependency>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-starter-test</artifactId>
            <scope>test</scope>
            <exclusions>
                <exclusion>
                    <groupId>org.junit.vintage</groupId>
                    <artifactId>junit-vintage-engine</artifactId>
                </exclusion>
            </exclusions>
        </dependency>
        <dependency>
            <groupId>javax.servlet</groupId>
            <artifactId>javax.servlet-api</artifactId>
            <version>4.0.1</version>
        </dependency>
    </dependencies>

    <build>
        <plugins>
            <plugin>
                <groupId>org.springframework.boot</groupId>
                <artifactId>spring-boot-maven-plugin</artifactId>
            </plugin>
        </plugins>
    </build>

</project>

启动器代码,注意要加@ServletComponentScan注解不然会404页面

package com.example;

import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.boot.web.servlet.ServletComponentScan;

@ServletComponentScan
@SpringBootApplication
public class DruidApplication {

    public static void main(String[] args) {
        SpringApplication.run(DruidApplication.class, args);
    }

}

properties:

# 实体类包路径
mybatis.type-aliases-package=com.example.model

spring.datasource.type= com.alibaba.druid.pool.DruidDataSource
spring.datasource.url=jdbc:mysql://localhost:3306/mybatis_springboot
spring.datasource.username=root
spring.datasource.password=root3306
spring.datasource.driver-class-name=com.mysql.jdbc.Driver

#初始化大小,最小,最大连接数
spring.datasource.druid.initial-size=3
spring.datasource.druid.min-idle=3
spring.datasource.druid.max-active=10

# 配置获取连接等待超时的时间
spring.datasource.druid.max-wait=60000

#监控后台账户和密码
spring.datasource.druid.stat-view-servlet.login-username=admin
spring.datasource.druid.stat-view-servlet.login-password=admin

#配置 StatFilter
spring.datasource.druid.filter.stat.log-slow-sql=true
spring.datasource.druid.filter.stat.slow-sql-millis=2000

配置servlet和filter

package com.example.druid;

import com.alibaba.druid.support.http.StatViewServlet;
import javax.servlet.annotation.WebInitParam;
import javax.servlet.annotation.WebServlet;

@WebServlet(urlPatterns = "/druid/*",
        initParams = {
                @WebInitParam(name="allow",value = "127.0.0.1"),
//                @WebInitParam(name="loginUsername",value = "admin",description = "druid用户名"),
//                @WebInitParam(name="loginPassword",value = "1234",description = "druid密码"),
                @WebInitParam(name="resetEnable",value = "false")
        })
public class DruidServlet extends StatViewServlet {
    private static final long serialVersionUID = 1L;
}
package com.example.druid;

import com.alibaba.druid.support.http.WebStatFilter;

import javax.servlet.annotation.WebFilter;
import javax.servlet.annotation.WebInitParam;

@WebFilter(
        filterName = "druidWebStatFilter",urlPatterns = "/*",
        initParams = {
                @WebInitParam( name="exclusions",value = "*.js,*.css,*.ico,/druid/*")
        }   )
public class DruidFilter extends WebStatFilter {

}

启动访问:http://localhost:8080/druid/login.html
在这里插入图片描述
输入配置文件中对应的账户密码登录:本文用的都是admin
在这里插入图片描述
以上就成功使用SpringBoot集成Druid监控数据源了,当然也可以接下来畅快的CURD了。当然我们觉得麻烦,java配置类结合配置文件觉得复杂,想单纯使用配置文件。

#开启servlet后台视图
spring.datasource.druid.stat-view-servlet.enabled=true

配置在properties中即可不用写servlet配置类,在启动类上也不需要写@ServletComponentScan了。

还有通常我们都需要放行一些资源文件,可以使用如下编写。

spring.datasource.druid.web-stat-filter.enabled=true
spring.datasource.druid.web-stat-filter.url-pattern=/*
spring.datasource.druid.web-stat-filter.exclusions=*.gif,*.png,*.jpg,*.html,*.js,*.css,*.ico,/druid/*

访问后台主页,效果同。

多数据源配置

# 数据源配置
spring:
    datasource:
        type: com.alibaba.druid.pool.DruidDataSource
        driverClassName: com.mysql.cj.jdbc.Driver
        druid:
            # 主库数据源
            master:
                url: jdbc:mysql://localhost:3306/ry?useUnicode=true&characterEncoding=utf8&zeroDateTimeBehavior=convertToNull&useSSL=true&serverTimezone=GMT%2B8
                username: root
                password: password
            # 从库数据源
            slave:
                # 从数据源开关/默认关闭
                enabled: false
                url: 
                username: 
                password: 
            # 初始连接数
            initialSize: 5
            # 最小连接池数量
            minIdle: 10
            # 最大连接池数量
            maxActive: 20
            # 配置获取连接等待超时的时间
            maxWait: 60000
            # 配置间隔多久才进行一次检测,检测需要关闭的空闲连接,单位是毫秒
            timeBetweenEvictionRunsMillis: 60000
            # 配置一个连接在池中最小生存的时间,单位是毫秒
            minEvictableIdleTimeMillis: 300000
            # 配置一个连接在池中最大生存的时间,单位是毫秒
            maxEvictableIdleTimeMillis: 900000
            # 配置检测连接是否有效
            validationQuery: SELECT 1 FROM DUAL
            testWhileIdle: true
            testOnBorrow: false
            testOnReturn: false
            webStatFilter: 
                enabled: true
            statViewServlet:
                enabled: true
                # 设置白名单,不填则允许所有访问
                allow:
                url-pattern: /druid/*
                # 控制台管理用户名和密码
                login-username: 
                login-password: 
            filter:
                stat:
                    enabled: true
                    # 慢SQL记录
                    log-slow-sql: true
                    slow-sql-millis: 1000
                    merge-sql: true
                wall:
                    config:
                        multi-statement-allow: true

更多学习,各种参数配置请参考druid官方。
https://github.com/alibaba/druid/tree/master/druid-spring-boot-starter

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
在 Spring Boot 中,可以通过添加 Druid Starter 依赖来集成 Druid 数据库连接池,同时可以通过在 application.yml 或 application.properties 文件中添加配置来启用 Druid 控制台。 以下是在 application.yml 中配置 druid 控制台的示例: ```yaml spring: datasource: url: jdbc:mysql://localhost:3306/testdb?useUnicode=true&characterEncoding=utf-8&useSSL=false&serverTimezone=GMT%2B8 username: root password: 123456 driver-class-name: com.mysql.cj.jdbc.Driver type: com.alibaba.druid.pool.DruidDataSource # Druid 监控配置 # Spring Boot 2.x 版本使用以下配置 servlet: # Druid 监控配置 registration: bean-name: druidStatViewServlet url-mappings: /druid/* # Druid 连接池监控配置 filter: # Druid 连接池监控配置 druid: # 配置 Druid 监控访问 http://localhost:8080/druid/ 即可看到监控页面 stat-view-servlet: enabled: true url-pattern: /druid/* reset-enable: false login-username: admin login-password: admin # 配置 Druid 连接池监控的 Filter,访问 http://localhost:8080/druid/api/ 即可看到监控数据 web-stat-filter: enabled: true url-pattern: /* exclusions: "*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*" session-stat-enable: true session-stat-max-count: 1000 principal-session-name: user profile-enable: true ``` 以上配置中,我们指定了数据库连接信息和 Druid 数据类型,并启用了 Druid监控功能。具体来说,我们配置了如下内容: - `servlet.registration.bean-name`:指定 Druid 监控 Servlet 的 Bean 名称,用于注册 Servlet。 - `servlet.registration.url-mappings`:指定 Druid 监控 Servlet 的 URL 映射,即访问该 URL 即可进入 Druid 监控页面。 - `filter.druid.stat-view-servlet.enabled`:是否启用 Druid 监控 Servlet。 - `filter.druid.stat-view-servlet.url-pattern`:指定 Druid 监控 Servlet 的 URL 映射,与 `servlet.registration.url-mappings` 一致。 - `filter.druid.stat-view-servlet.login-username` 和 `filter.druid.stat-view-servlet.login-password`:用于登录 Druid 监控页面的用户名和密码。 - `filter.druid.web-stat-filter.enabled`:是否启用 Druid 连接池监控 Filter。 - `filter.druid.web-stat-filter.url-pattern`:指定 Druid 连接池监控 Filter 的 URL 映射。 - `filter.druid.web-stat-filter.exclusions`:指定 Druid 连接池监控 Filter 排除的 URL。 - `filter.druid.web-stat-filter.session-stat-enable`:是否开启 Session 统计功能。 - `filter.druid.web-stat-filter.session-stat-max-count`:指定 Session 统计最大数量。 - `filter.druid.web-stat-filter.principal-session-name`:指定 Session 中保存用户信息的属性名称。 - `filter.druid.web-stat-filter.profile-enable`:是否启用 SQL 监控功能。 配置完成后,我们就可以通过访问配置的 URL 来查看 Druid 监控页面了。在页面上,我们可以查看连接池的使用情况、SQL 执行情况、SQL 监控等信息。

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值