Druid

What is a Druid

  1. A large portion of Java programs operate on databases, and to improve performance, they have to use database connection pools.

  2. Druid is a database connection pool implementation on Alibaba’s open source platform. It combines the advantages of C3P0, DBCP, and log monitoring.

  3. Druid is designed to monitor DB connections and SQL execution.

  4. Druid has already deployed more than 600 applications on Alibaba, and has been rigorously deployed in a production environment for over a year.

  5. Hikari and Driud are among the best data sources on the Java Web. We’ll focus on how Spring Boot integrates with Druid data sources. How to implement database monitoring.

The use of the Druid

Preparatory work

  1. Check this box when creating a New SpringBoot projectspring web,JDBC APIandMySQL Driver.
  2. In the POM.xml configuration file, addlog4jDependency anddruidRely on
<! --log4j-->
<dependency>
    <groupId>log4j</groupId>
    <artifactId>log4j</artifactId>
    <version>1.2.17</version>
</dependency>

<! -- https://mvnrepository.com/artifact/com.alibaba/druid -->
<! --druid-->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.2.5</version>
</dependency>
Copy the code

use

  1. inapplication.ymlConfigure the Druid data source
spring:
  datasource:
    username: root
    password: 123456
    url: jdbc:mysql://localhost:3306/mybatis? serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource # Custom data source

    #Spring Boot does not inject these property values by default, you need to bind them yourself
    #druid Data source proprietary configuration
    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

    # Configure filters to monitor statistics interception, stat: monitor statistics, log4j: logging, wall: defend against SQL injection
    # if allowed times wrong Java. Lang. ClassNotFoundException: org.. Apache log4j. Priority
    # import log4j dependence can, Maven address: https://mvnrepository.com/artifact/log4j/log4j
    filters: stat,wall,log4j
    maxPoolPreparedStatementPerConnectionSize: 20
    useGlobalDataSourceStat: true
    connectionProperties: druid.stat.mergeSql=true; druid.stat.slowSqlMillis=500
Copy the code
  1. addDruidDataSource Component into a container and bind properties;
    /* Add a custom Druid data source to the container. No longer let Spring Boot automatically created Binding druid in the global configuration file data source properties to com. Alibaba. The druid. Pool. DruidDataSource which allow them to take effect @ ConfigurationProperties (prefix = "spring. The datasource") : Role is to global configuration file Prefix for spring. The datasource attribute value into com. Alibaba. The druid. Pool. DruidDataSource * / in the parameters of the same name
    @Bean
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource(a){
        return new DruidDataSource();
    }
Copy the code
  1. Simply test if our data source is Druid
package com.example;

import com.alibaba.druid.pool.DruidDataSource;
import org.junit.jupiter.api.Test;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;

import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;


@SpringBootTest
class Springboot05DataApplicationTests {

    @Autowired
    DataSource dataSource;

    @Test
    void contextLoads(a) throws SQLException {

        // Check the data source type
        System.out.println(dataSource.getClass());

        // Get the connection
        Connection connection = dataSource.getConnection();

        System.out.println(connection);

        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        System.out.println(DruidDataSource gets maximum number of connections:+druidDataSource.getMaxActive());
        System.out.println(DruidDataSource initial number of connections:+druidDataSource.getInitialSize());

        // Close the connectionconnection.close(); }}Copy the code

Special features of Druid

Background monitoring function

 //druid
    // There is no web. XML file with the built-in Servlet container, so use Spring Boot to register servlets
    @Bean// Configure the Servlet for Druid. Equivalent to a web.xml file
    public ServletRegistrationBean statViewServlet(a) {
    
        ServletRegistrationBean bean =
                new ServletRegistrationBean(new StatViewServlet(), "/druid/*");


        Map<String, String> initParams = new HashMap<>();
        // The login account is fixed and cannot be changed
        initParams.put("loginUsername"."admin");
        //// The login password is fixed and cannot be changed
        initParams.put("loginPassword"."123456");

        // Who is allowed to access the background
        // initparams. put("allow", "localhost") : indicates that only the localhost is accessible
        // initparams. put("allow", "") : If empty or null, all access is allowed
        initParams.put("allow"."");

        // Disable Xiaomi from accessing
        / / initParams. Put (" xiaomi ", "192.168.1.20");

        // Initialize parameters
        bean.setInitParameters(initParams);

        return bean;
    }
Copy the code

Configure the Druid web monitoring filter

    // Configure the Druid web monitoring filter
    public FilterRegistrationBean webStatFilter(a) {
        FilterRegistrationBean bean = new FilterRegistrationBean();

        bean.setFilter(new WebStatFilter());

        // Exclusions: Specifies requests that can be filtered and excluded so that statistics are not collected
        Map<String, String> initParams = new HashMap<>();
        initParams.put("exclusions"."*.js,*.css,/druid/*,/jdbc/*");
        bean.setInitParameters(initParams);

        // "/*" filters all requests
        bean.setUrlPatterns(Arrays.asList("/ *"));


        return bean;
    }
Copy the code