内容目录

1.引言

在本教程中,我们将深入探讨如何使用springboot 整合alibaba的driud数据库监控工具,监控 SQL 执行情况。我们将讨论如何安装和配置 Druid,以及如何使用 Druid 监控 SQL 执行情况。我们将用一些示例来说明如何安装和配置 Druid,并且会提供一些实用的技巧和建议,以帮助开发者更好地使用它们。
精通Spring Boot
alibaba已经提供了spring-boot-starter的jar包了。先看pom.xml加个依赖~~ (druid.version自己找哈) 。

 <!--阿里巴巴druid数据库管理-->
  <dependency>
     <groupId>com.alibaba</groupId>
     <artifactId>druid-spring-boot-starter</artifactId>
     <version>${druid.version}</version>
  </dependency>

2.druid配置

配置信息是少不了滴~~

# 开发环境下配置
spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/test?allowMultiQueries:true&characterEncoding:UTF-8&zeroDateTimeBehavior:convertToNull
      username: root
      password: 123456
      driver-class-name: com.mysql.jdbc.Driver
      # 连接池配置
      initial-size: 1
      max-active: 20
      min-idle: 1
      max-wait: 10000
      pool-prepared-statements: true
      max-open-prepared-statements: 20
      validation-query: SELECT 1 FROM DUAL
      validation-query-timeout: 5000
      test-on-borrow: false
      test-on-return: false
      test-while-idle: true
      time-between-eviction-runs-millis: 60000
      min-evictable-idle-time-millis: 30000
      max-evictable-idle-time-millis: 60000
      removeAbandoned: true
      removeAbandonedTimeout: 1800
      connectionProperties: druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
      max-pool-prepared-statement-per-connection-size: 20
      filters: stat,wall #filters: #配置多个英文逗号分隔(统计,sql注入,log4j过滤)
    type: com.alibaba.druid.pool.DruidDataSource

3.druid的Configuration配置

接下来是重点,重点,重点……@Configuration注解的配置类

@Configuration
public class DruidConfig {

    private static final Logger logger = LoggerFactory.getLogger(DruidConfig.class);

    @Autowired
    private AppConfig appConfig;

    @Value("${spring.datasource.druid.url}")
    private String dbUrl;

    @Value("${spring.datasource.druid.username}")
    private String username;

    @Value("${spring.datasource.druid.password}")
    private String password;

    @Value("${spring.datasource.druid.driver-class-name}")
    private String driverClassName;

    @Value("${spring.datasource.druid.initial-size}")
    private int initialSize;

    @Value("${spring.datasource.druid.min-idle}")
    private int minIdle;

    @Value("${spring.datasource.druid.max-active}")
    private int maxActive;

    @Value("${spring.datasource.druid.max-wait}")
    private int maxWait;

    @Value("${spring.datasource.druid.time-between-eviction-runs-millis}")
    private int timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.druid.min-evictable-idle-time-millis}")
    private int minEvictableIdleTimeMillis;

    @Value("${spring.datasource.druid.validation-query}")
    private String validationQuery;

    @Value("${spring.datasource.druid.test-while-idle}")
    private boolean testWhileIdle;

    @Value("${spring.datasource.druid.test-on-borrow}")
    private boolean testOnBorrow;

    @Value("${spring.datasource.druid.test-on-return}")
    private boolean testOnReturn;

    @Value("${spring.datasource.druid.pool-prepared-statements}")
    private boolean poolPreparedStatements;

    @Value("${spring.datasource.druid.max-pool-prepared-statement-per-connection-size}")
    private int maxPoolPreparedStatementPerConnectionSize;

    @Value("${spring.datasource.druid.filters}")
    private String filters;

    @Value("{spring.datasource.druid.connection-properties}")
    private String connectionProperties;

    @Bean     //声明其为Bean实例
    @Primary  //在同样的DataSource中,首先使用被标注的DataSource
    public DataSource dataSource() {
        DruidDataSource datasource = new DruidDataSource();
        datasource.setUrl(dbUrl);
        datasource.setUsername(username);
        datasource.setPassword(password);
        datasource.setDriverClassName(driverClassName);
        //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 {
            datasource.setFilters(filters);
        } catch (Exception e) {
            logger.error("druid configuration initialization filter", e);
        }
        datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }

    @Bean
    public ServletRegistrationBean druidServlet() {
        //logger.info("init Druid Servlet Configuration ");
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean();
        servletRegistrationBean.setServlet(new StatViewServlet());
        servletRegistrationBean.addUrlMappings("/druid/*");
        Map<String, String> initParameters = new HashMap<>();
        initParameters.put("loginUsername", appConfig.getDruidUserName());// 用户名
        initParameters.put("loginPassword", appConfig.getDruidPassword());// 密码
        initParameters.put("resetEnable", appConfig.getDruidResetAll());// 禁用HTML页面上的“Reset All”功能
        initParameters.put("allow", ""); // IP白名单 (没有配置或者为空,则允许所有访问)
        //initParameters.put("deny", "192.168.20.38");// IP黑名单 (存在共同时,deny优先于allow)
        servletRegistrationBean.setInitParameters(initParameters);
        return servletRegistrationBean;
    }

    @Bean
    public FilterRegistrationBean druidWebStatViewFilter() {
        FilterRegistrationBean registrationBean = new FilterRegistrationBean(new WebStatFilter());
        registrationBean.addInitParameter("urlPatterns", "/*");
        registrationBean.addInitParameter("exclusions", "*.js,*.gif,*.jpg,*.bmp,*.png,*.css,*.ico,/druid/*");
        return registrationBean;
    }
}

4.自定义AppConfig类

这里解释说下,AppConfig类是我自定义的一些配置项目,和集成druid没有关系噢。
到这就可以写个连接数据库查询测试下druid了,在地址栏输入localhost:8080/druid 就能访问druid的登录页面了。

image

通过本教程,我们已经了解了如何使用 Spring Boot 整合 Druid 监控 SQL 执行情况。
Spring Boot 提供了许多功能和特性来帮助开发者更好地开发 Web 应用程序。Druid 是一个非常强大和灵活的数据库连接池和监控工具,Spring Boot 还可以通过其 Actuator 进行管理和监控,使得开发者可以更方便地使用 Druid 来管理和监控数据库。

上一篇教程:精通Spring Boot: DispatcherServlet和Multipart配置

最后,以上示例代码可在我的github.com中找到。

By liu luli

8年IT行业从业经验,参与、负责过诸多大型项目建设。掌握多门编程语言,对Java、Python编程有较为深刻的理解。现为杭州某公司开发负责人。

One thought on “精通Spring Boot : 整合druid监控SQL执行”

发表回复

您的邮箱地址不会被公开。 必填项已用 * 标注