SpringBoot如何配置Druid数据源监控页面

2023年1月16日11:58:34

简介

什么是Druid?

Druid是阿里巴巴开发的,其号称为监控而生的数据源。Druid是目前最好的数据库数据源,它在功能、性能、扩展性方面,都超过其他数据库连接池,比如dbcp、c3p0、BoneCP、Proxool、JBoss DataSource。

SpringBoot上配置Druid

在SpringBoot上配置相当简单,只需3步即可。

  1. 添加druid依赖
    <dependency>
        <groupId>com.alibaba</groupId>
        <artifactId>druid</artifactId>
        <version>1.1.23</version>
    </dependency>
    
  2. 在配置文件中切换数据源
    SpringBoot如何配置Druid数据源监控页面
    可选择添加以下配置
# Spring Boot 默认是不注入这些属性值的,需要自己绑定
# druid 数据源专有配置
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,stat:监控统计、log4j:日志记录、wall:防御sql注入
filters: stat,wall,log4j
maxPoolPreparedStatementPerConnectionSize: 20
useGlobalDataSourceStat: true
connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=500

注意:如果允许时报错 java.lang.ClassNotFoundException: org.apache.log4j.Priority, 则导入 log4j 依赖即可,Maven 地址:https://mvnrepository.com/artifact/log4j/log4j

  1. 需要自己添加 DruidDataSource 组件到容器中,并绑定属性
@Configuration
public class DruidConfig {

    @ConfigurationProperties(prefix = "spring.datasource")
    @Bean
    public DataSource druidDataSource() {
        return new DruidDataSource();
    }
}

配置Druid数据源监控页面

Druid 数据源具有监控的功能,并提供了一个 web 界面方便用户查看,类似安装路由器时,druid 也提供了一个默认的 web 页面。

开始配置:(继续在刚创建的DruidConfig中配置)

(暂记能配置的参数都在 ResourceServlet 里 )

  1. 需要设置 Druid 的后台管理页面,比如登录账号、密码等,配置后台管理;

    // 内置没有web.xml文件,使用 SpringBoot 注册 Servlet 方式配置
    @Bean
    public ServletRegistrationBean statViewServlet() {
        ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");
    
        // 这些参数可以在StatViewServlet 的父类 ResourceServlet 中找到
        Map<String, String> initParams = new HashMap<>();
        initParams.put("loginUsername", "admin"); //后台管理界面的登录账号
        initParams.put("loginPassword", "123456"); //后台管理界面的登录密码
    
     	// 页面允许某用户可以访问
        // initParams.put("allow", "localhost"):表示只有本机可以访问
        
        // 第二参数为空或者为null时,表示允许所有访问
        initParams.put("allow", "");
        
        // 页面拒绝xxx访问
        // initParams.put("xxx", "127.0.0.1"):表示禁止此ip访问
    
        // 设置初始化参数
        bean.setInitParameters(initParams);
        return bean;
    }
    
  2. 配置完毕后,访问 http://localhost:8080/druid/login.html 进入页面

  3. 输入刚才配置的用户名和密码即可登入到druid监控页面

遇到问题

  • 我编写时遇到的问题:在 new StatViewServlet()时,出现了错误,无法被创建出来。
  • 解决:点进源码查看时,发现关于servlet的包全部都报红了,所以在maven pom 中导入了servlet,就可以创建了。
    • 注意:导入的servlet包要3.0+,要不会没有ServletRegistrationMultipartConfigElement

愿世上没有Bug

  • 作者:关耳布
  • 原文链接:https://blog.csdn.net/PINKMIAO/article/details/108438680
    更新时间:2023年1月16日11:58:34 ,共 2158 字。