Example analysis of the method of configuring Druid data source with springboot

Time:2021-5-2

This paper describes the method of configuring the Druid data source with springboot. The details are as follows:

Druid is an open source database connection pool of Alibaba.

Integration of Druid data source process during development.

1. Modify pom.xml


<dependency>
  <groupId>mysql</groupId>
  <artifactId>mysql-connector-java</artifactId>
</dependency>
<dependency>
  <groupId>com.alibaba</groupId>
  <artifactId>druid</artifactId>
  <version>1.0.26</version>
</dependency>

Add the above configuration.

2. Edit and configure data source code

package com.neo.conf;
import javax.sql.DataSource;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.boot.web.servlet.FilterRegistrationBean;
import org.springframework.boot.web.servlet.ServletRegistrationBean;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.context.annotation.PropertySource;
import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.support.http.StatViewServlet;
import com.alibaba.druid.support.http.WebStatFilter;
@Configuration
@ConfigurationProperties(value = "classpath:druid.properties")
public class DruidConfiguration {
  @Bean(destroyMethod = "close", initMethod = "init")
  @ConfigurationProperties(prefix = "spring.datasource")
  public DataSource druidDataSource() {
    DruidDataSource druidDataSource = new DruidDataSource();
    return druidDataSource;
  }
  /**
   *Register a statviewservlet
   * @return
   */
  @Bean
  public ServletRegistrationBean druidStatViewServlet(){
    //Org. Springframework. Boot. Context. Embedded. Servletregistrationbean provides class registration
    ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
    //Add initialization parameter: initparams
    //White list:
    servletRegistrationBean.addInitParameter("allow","127.0.0.1,192.168.31.77");
    //IP blacklist (deny is prior to allow when there are common): if deny is met, prompt: sorry, you are not permitted to view this page
    servletRegistrationBean.addInitParameter("deny","192.168.1.73");
    //Login to view the account password of the information
    servletRegistrationBean.addInitParameter("loginUsername","admin");
    servletRegistrationBean.addInitParameter("loginPassword","123456");
    //Whether the data can be reset
    servletRegistrationBean.addInitParameter("resetEnable","false");
    return servletRegistrationBean;
  }
  /**
   *Register a: filterregistrationbean
   * @return
   */
  @Bean
  public FilterRegistrationBean druidStatFilter(){
    FilterRegistrationBean filterRegistrationBean = new FilterRegistrationBean(new WebStatFilter());
    //Add filtering rules
    filterRegistrationBean.addUrlPatterns("/*");
    //Add format information that doesn't need to be ignored
    filterRegistrationBean.addInitParameter("exclusions","*.js,*.gif,*.jpg,*.png,*.css,*.ico,/druid/*");
    return filterRegistrationBean;
  }
}

3. Write the configuration file druid.properties

spring.datasource.driverClassName=com.mysql.jdbc.Driver
spring.datasource.url=jdbc:mysql://localhost:3306/mycine?useUnicode=true&characterEncoding=utf8&autoReconnect=true
spring.datasource.username=root
spring.datasource.password=root
#--------------------------
#The following is the supplementary setting of connection pool, which is applied to all data sources above
#Initialization size, minimum, maximum
spring.datasource.initialSize=5
spring.datasource.minIdle=5
spring.datasource.maxActive=50
#Configure the time to wait for a connection to time out
spring.datasource.maxWait=60000
#Configure how often to detect the idle connections that need to be closed, in milliseconds
spring.datasource.timeBetweenEvictionRunsMillis=60000
#Configure the minimum lifetime of a connection in the pool, in milliseconds
spring.datasource.minEvictableIdleTimeMillis=300000
spring.datasource.validationQuery=SELECT 1
spring.datasource.testWhileIdle=true
spring.datasource.testOnBorrow=false
spring.datasource.testOnReturn=false
#Turn on pscache and specify the size of pscache on each connection
spring.datasource.poolPreparedStatements=false
#spring.datasource.maxPoolPreparedStatementPerConnectionSize=20
#Configure the filters for monitoring and statistics interception. After removing the filters, SQL in the monitoring interface can't make statistics, and 'wall' is used for firewall
#spring.datasource.filters=stat,wall,log4j
spring.datasource.filters=stat
#The function of mergesql is opened through the property of connectproperties; Slow SQL record
spring.datasource.connectionProperties=druid.stat.mergeSql=true;druid.stat.slowSqlMillis=5000
#Merging monitoring data from multiple druiddatasources
#spring.datasource.useGlobalDataSourceStat=true

4. Start the program to check the effect

More about Java related content, interested readers can see our special topics: “spring framework introduction and advanced tutorial”, “Java data structure and algorithm tutorial”, “Java operation DOM node skills summary”, “java file and directory operation skills summary” and “Java cache operation skills summary”

I hope this article will be helpful to you in Java programming.

Recommended Today

Common auxiliary classes

CountDownLatch Subtraction counter import java.util.concurrent.CountDownLatch; //Counter public class CountDownLatchDemo { public static void main(String[] args) throws InterruptedException { //The total number is 6. It can be used when the task must be performed CountDownLatch countDownLatch = new CountDownLatch(6); for (int i = 0; i < 6; i++) { new Thread(()->{ System.out.println(Thread.currentThread().getName()+” Go out”); countDownLatch.countDown(); },String.valueOf(i)).start(); […]