On the database connection pool druid (springboot)

Database principle part of the pool

Role: The basic idea is the connection pool when the system is initialized, the database connection is stored as objects in memory when the user needs to access the database, not the establishment of a new connection, but remove idle established a connection from the pool connection object . After use, the user is not the connection is closed, but the connection back to the connection pool to use for the next access request. The establishment of the connection, disconnection by the connection pool to manage itself . Meanwhile, the initial number may also be controlled by setting the connection pool connection pool parameters, the minimum number of connections and the maximum number of use of each connection, and so the maximum idle time. May be monitored by a number of its own database connection management mechanism, usage and the like.

The main influence factors:

  1. The minimum number of connections to
    the database connection pool has been maintained, so if the amount of the application to the database is not connected, there will be a large number of database connection resources are wasted.
  2. The maximum number of connections
    is the maximum number of connection pools can apply, if the database connection requests exceeding this number, the database connection request to be added later to the waiting queue, which will affect subsequent database operations.
  3. The minimum number of connections and the maximum number of connections gap
    minimum number of connections and the maximum number of connections that much difference, then the connection request will be the first to profit, after more than a minimum number of connections equivalent to a connection request to establish a connection to the new database. However, these larger than the minimum number of connections is not finished using the database connection is released immediately, it is placed in the connection pool after waiting for the idle timeout reused or released.

Configuration springboot the druid database pool

Reference article:
(more detailed)

Using oracle database: https://blog.csdn.net/shmily_lsl/article/details/88035791

First, import-dependent:

<!-- 阿里系的Druid依赖包 -->
        <dependency>
            <groupId>com.alibaba</groupId>
            <artifactId>druid-spring-boot-starter</artifactId>
            <version>1.1.9</version>
        </dependency>
        <!-- Druid 依赖 log4j包 -->
        <dependency>
            <groupId>log4j</groupId>
            <artifactId>log4j</artifactId>
            <version>1.2.17</version>
        </dependency>

Profile application.yml

spring:
  datasource:
    druid:
      url: jdbc:mysql://localhost:3306/test?serverTimezone=UTC&useUnicode=true&characterEncoding=utf-8&useSSL=true
      username: root
      password: root
      driver: com.mysql.cj.jdbc.Driver
      initial-size: 10
      max-active: 10000
      min-idle: 2
      max-wait: 6000
      time-between-eviction-runs-millis: 60000
      timeBetweenEvictionRunsMillis: 60000
      minEvictableIdleTimeMillis: 300000
      #  是否缓存preparedStatement,也就是PSCache。PSCache对支持游标的数据库性能提升巨大,比如说oracle。在mysql下建议关闭。
      pool-prepared-statements: false
      validation-query: select 1 from dual
      validation-query-timeout: 100000
      # 申请连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能。 建议false
      test-on-borrow: false
      # 归还连接时执行validationQuery检测连接是否有效,做了这个配置会降低性能 ,建议false
      test-on-return: false
      test-while-idle: true
      max-pool-prepared-statement-per-connection-size: 20
      filters: stat

DBDruidConfig

@Configuration
public class DBDruidConfig {

    private static Logger logger = LogManager.getLogger(DBDruidConfig.class);

    @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}")
    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 long maxWait;

    @Value("${spring.datasource.druid.timeBetweenEvictionRunsMillis}")
    private long timeBetweenEvictionRunsMillis;

    @Value("${spring.datasource.druid.minEvictableIdleTimeMillis}")
    private long minEvictableIdleTimeMillis;

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

    @Value("${spring.datasource.druid.validation-query-timeout}")
    private int validationQueryTimeout;

    @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.filters}")
    private String filters;

    /*
    meger操作
    @Value("{spring.datasource.connectionProperties}")
    private String connectionProperties;*/

    @Bean(name = "druidDataSource")     //声明其为Bean实例
    @Primary  //在同样的DataSource中,首先使用被标注的DataSource
    public DruidDataSource dataSource(){
        DruidDataSource datasource = new DruidDataSource();

        datasource.setUrl(this.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.setValidationQueryTimeout(validationQueryTimeout);
        datasource.setTestWhileIdle(testWhileIdle);
        datasource.setTestOnBorrow(testOnBorrow);
        datasource.setTestOnReturn(testOnReturn);
        datasource.setPoolPreparedStatements(poolPreparedStatements);
        try {
            datasource.setFilters(filters);
        } catch (SQLException e) {
            logger.error("druid configuration initialization filter", e);
        }
        //datasource.setConnectionProperties(connectionProperties);

        return datasource;
    }

    @Bean
    public ServletRegistrationBean statViewServlet(){
        //创建servlet注册实体
        ServletRegistrationBean servletRegistrationBean = new ServletRegistrationBean(new StatViewServlet(),"/druid/*");
        //设置ip白名单
        servletRegistrationBean.addInitParameter("allow","127.0.0.1");
        //设置ip黑名单
        servletRegistrationBean.addInitParameter("deny","192.168.0.2");
        //设置控制台管理用户__登录用户名和密码
        servletRegistrationBean.addInitParameter("loginUsername","druid");
        servletRegistrationBean.addInitParameter("loginPassword","123456");
        //是否可以重置数据
        servletRegistrationBean.addInitParameter("resetEnable","false");
        return servletRegistrationBean;
    }
}

After running the project, visit http: // localhost: 8080 / druid / sql.html,

Here Insert Picture Description

Enter your user name and password on it

Here Insert Picture Description
Source: https://github.com/jiaojiaoyow/mybatis-pool.git

Published 36 original articles · won praise 11 · views 10000 +

Guess you like

Origin blog.csdn.net/s_xchenzejian/article/details/97132507