Spring boot08: integrating Druid

Crazy God said that the spring boot series is easy to understand. Based on the version 2.2.5 of spring boot, you are welcome to forward and pay attention to learning.

WeChat official account: Bilibili, the first of the gods, Java

No reprint without authorization of the author

Integrated Druid

About Druid

A large part of Java program needs to operate database. In order to improve the performance of database operation, database connection pool has to be used.

Druid is a database connection pool implementation on Alibaba open source platform. It combines the advantages of C3P0, DBCP and other DB pools, and adds log monitoring.

Druid can monitor the connection of DB pool and the execution of SQL very well. It is a DB connection pool born for monitoring.

Druid has deployed more than 600 applications in Alibaba, which has passed the severe test of large-scale deployment of production environment for more than one year.

Spring Boot 2.0 uses Hikari data source by default. It can be said that Hikari and Driud are the best data sources on Java Web at present. Let's focus on how Spring Boot integrates Druid data source and how to realize database monitoring.

Github address: https://github.com/alibaba/druid/

com.alibaba.druid.pool.DruidDataSource The basic configuration parameters are as follows:




Configure data sources

1. Add a Druid data source dependency on.

<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->

2. Switch the data source; it has been said that Spring Boot 2.0 is used by default com.zaxxer.hikari.HikariDataSource data source, but you can use the spring.datasource.type Specify the data source.

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

3. After the data source is switched, inject DataSource into the test class, then get it, and the output will know whether the switch is successful or not;

4. Switch succeeded! Since the switch is successful, you can set the initialization size of data source connection, the maximum number of connections, the waiting time, the minimum number of connections and other settings; you can view the source code

    username: root
    password: 123456
    #? serverTimezone=UTC to resolve time zone error
    url: jdbc:mysql://localhost:3306/springboot?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8
    driver-class-name: com.mysql.cj.jdbc.Driver
    type: com.alibaba.druid.pool.DruidDataSource

    #Spring Boot does not inject these attribute values by default, and needs to bind by itself
    #druid data source specific 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 for monitoring statistics interception, stat: monitoring statistics, log4j: logging, wall: defending sql injection
    #If you allow me to make a mistake java.lang.ClassNotFoundException: org.apache.log4j.Priority
    #Then import log4j dependency. 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

5. Import Log4j dependency

<!-- https://mvnrepository.com/artifact/log4j/log4j -->

6. Now we need the programmer to bind the parameters in the global configuration file for DruidDataSource and add them to the container, instead of using Spring Boot to generate automatically; we need to add the DruidDataSource component to the container and bind the properties;

package com.kuang.config;

import com.alibaba.druid.pool.DruidDataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import javax.sql.DataSource;

public class DruidConfig {

       Add the custom Druid data source to the container and no longer let Spring Boot create it automatically
       Bind the Druid data source attribute in the global configuration file to com.alibaba.druid.pool.DruidDataSource So that they work
       @ConfigurationProperties(prefix = "spring.datasource"): The function is to
       Prefix is spring.datasource Property values injected into com.alibaba.druid.pool.DruidDataSource  In the parameter with the same name of
    @ConfigurationProperties(prefix = "spring.datasource")
    public DataSource druidDataSource() {
        return new DruidDataSource();


7. Go to test class to see if it is successful!

class SpringbootDataJdbcApplicationTests {

    //DI Inject data source
    DataSource dataSource;

    public void contextLoads() throws SQLException {
        //Take a look at the default data source
        //Get connected
        Connection connection =   dataSource.getConnection();

        DruidDataSource druidDataSource = (DruidDataSource) dataSource;
        System.out.println("druidDataSource Data source maximum connections:" + druidDataSource.getMaxActive());
        System.out.println("druidDataSource Number of data source initialization connections:" + druidDataSource.getInitialSize());

        //Close connection

Output result: visible configuration parameters have taken effect!


Configure Druid data source monitoring

Druid data source has the function of monitoring, and provides a web interface for users to view. Similar to installing a router, people also provide a default web page.

So the first step is to set Druid's background management page, such as login account, password, etc.; configure background management;

//to configure Druid Monitoring management background Servlet;
//built-in Servlet No container web.xml File, so use Spring Boot 's registration Servlet mode
public ServletRegistrationBean statViewServlet() {
    ServletRegistrationBean bean = new ServletRegistrationBean(new StatViewServlet(), "/druid/*");

    // These parameters can be com.alibaba.druid.support.http.StatViewServlet 
    // Parent of com.alibaba.druid.support.http.ResourceServlet Found in
    Map<String, String> initParams = new HashMap<>();
    initParams.put("loginUsername", "admin"); //Login account of background management interface
    initParams.put("loginPassword", "123456"); //Login password of background management interface

    //Who is allowed access in the background
    //initParams.put("allow", "localhost"): Indicates that only the local machine can access
    //initParams.put("allow", ""): Empty or null When, all access is allowed
    initParams.put("allow", "");
    //deny: Druid Who is denied access in the background
    //initParams.put("kuangshen", "");Indicates that this is prohibited ip visit

    //Set initialization parameters
    return bean;

After configuration, we can choose to access: http://localhost:8080/druid/login.html

After entering

Configure Druid web monitoring filter

//to configure Druid Monitoring  web Monitored filter
//WebStatFilter: For configuration Web and Druid Management Association monitoring statistics between data sources
public FilterRegistrationBean webStatFilter() {
    FilterRegistrationBean bean = new FilterRegistrationBean();
    bean.setFilter(new WebStatFilter());

    //exclusions: Set which requests to filter and exclude so as not to make statistics
    Map<String, String> initParams = new HashMap<>();
    initParams.put("exclusions", "*.js,*.css,/druid/*,/jdbc/*");

    //"/*" Indicates filtering all requests
    return bean;

Usually in the work, according to the needs of the configuration can be, mainly used for monitoring!

Tags: Druid Spring log4j Database

Posted on Tue, 26 May 2020 00:58:17 -0400 by davelr459