美文网首页Spring技巧
SpringBoot druid view 数据源监控视图

SpringBoot druid view 数据源监控视图

作者: 饱饱想要灵感 | 来源:发表于2023-07-25 13:36 被阅读0次

    在 Spring Boot 中启用 Druid View 需要以下步骤:

    1. 添加 Druid Starter 依赖到你的项目的 pom.xml 文件中:
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid-spring-boot-starter</artifactId>
        <version>1.2.6</version>
    </dependency>
    
    1. 在你的 Spring Boot 应用的配置文件(如 application.propertiesapplication.yml)中配置 Druid 数据源:
    spring.datasource.url=jdbc:mysql://localhost:3306/mydatabase
    spring.datasource.username=myusername
    spring.datasource.password=mypassword
    spring.datasource.driver-class-name=com.mysql.jdbc.Driver
    

    或者使用 YAML 格式的配置:

    spring:
      datasource:
        url: jdbc:mysql://localhost:3306/mydatabase
        username: myusername
        password: mypassword
        driver-class-name: com.mysql.jdbc.Driver
    
    1. 在你的 Spring Boot 应用的配置文件中配置 Druid View:
    spring.datasource.druid.stat-view-servlet.enabled=true
    spring.datasource.druid.stat-view-servlet.url-pattern=/druid/*
    spring.datasource.druid.stat-view-servlet.allow=127.0.0.1
    spring.datasource.druid.stat-view-servlet.login-username=admin
    spring.datasource.druid.stat-view-servlet.login-password=admin123
    

    或者使用 YAML 格式的配置:

    spring:
      datasource:
        druid:
          filters: stat,wall,log4j
          login-username: admin
          login-password: admin_password
          # 配置IP白名单限制
          allow: 127.0.0.1
          # 如果有多个IP,可以使用逗号分隔
          # allow: 127.0.0.1,192.168.0.1
          # 或者使用IP段
          # allow: 127.0.0.1/24
    

    在上述配置中,druid.filters 配置用于设置Druid的过滤器:

    • stat:用于统计SQL语句的执行情况,包括执行次数、执行时间等信息。
    • wall:用于SQL的防火墙,可以防止SQL注入攻击。
    • log4j:用于将SQL执行的日志输出到log4j日志中

    login-usernamelogin-password 分别用于设置登录用户名和密码。allow 配置用于设置允许访问Druid的IP地址,可以是单个IP地址,多个IP地址(使用逗号分隔),或者IP段(使用斜杠加上掩码位数)。

    也可以使用java配置类的方式:

    @Configuration
    public class DruidConfig {
    
        @Bean
        public ServletRegistrationBean statViewServlet() {
            ServletRegistrationBean registrationBean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
            registrationBean.addInitParameter("loginUsername", "admin");
            registrationBean.addInitParameter("loginPassword", "admin123");
            registrationBean.addInitParameter("allow", "127.0.0.1");
            return registrationBean;
        }
    }
    

    上述配置中,loginUsernameloginPassword分别用于设置访问Druid StatView的账号和密码,allow表示可以访问的IP地址, url-pattern用于设置访问StatViewServlet的路径。可以根据实际情况进行调整。

    1. 启动你的 Spring Boot 应用,访问 http://localhost:8080/druid/ 即可进入 Druid View 的管理界面。你可以使用配置文件中设置的用户名和密码进行登录。

    相关文章

      网友评论

        本文标题:SpringBoot druid view 数据源监控视图

        本文链接:https://www.haomeiwen.com/subject/zihhpdtx.html