Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

What are the configuration parameters of Java database connection pool Druid

2025-01-30 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/02 Report--

This article mainly introduces "what are the configuration parameters of Java database connection pool Druid". In the daily operation, I believe that many people have doubts about the configuration parameters of Java database connection pool Druid. The editor consulted all kinds of materials and sorted out simple and easy-to-use operation methods. I hope it will be helpful to answer the doubts of "what are the configuration parameters of Java database connection pool Druid?" Next, please follow the editor to study!

1. Configuration parameters

The configuration parameters of Druid connection pool are compatible with DBCP, and the semantics of individual configurations are different.

The default value for configuring name indicates that the significance of configuring this property is that if there are multiple data sources, monitoring can be distinguished by name. If it is not configured, a name will be generated in the format "DataSource-" + System.identityHashCode (this). Configure this property version to at least 1.0.5, and setting name below this version will cause errors.

User name of url connection database urlusername connection database password of password connection database. If you don't want the password to be written directly in the configuration file, you can use ConfigFilter.

DriverClassName automatically identifies this option according to url. If Druid is not configured, dbType will be automatically identified according to url, and then the number of physical connections will be established during initialization by selecting the corresponding driverClassNameinitialSize0. Initialization occurs when the call to the init method is displayed, or the maximum number of connection pools in maxActive8 is no longer used when the first getConnection is used. If configured, there is no effect on the minimum number of connection pools in minIdle. The maximum waiting time (in milliseconds) when maxWait acquires connections. After maxWait is configured, fair locks are enabled by default, and concurrency efficiency decreases, and unfair locks can be used for true by configuring the useUnfairLock attribute if necessary. Whether poolPreparedStatementsfalse caches preparedStatement, that is, PSCache. PSCache greatly improves the performance of databases that support cursors, such as oracle. It is recommended to close under mysql. For maxPoolPreparedStatementPerConnectionSize-1 to enable PSCache, it must be configured greater than 0. When it is greater than 0, poolPreparedStatements automatically triggers the modification to true. In Druid, there is no problem that PSCache takes up too much memory under Oracle. You can configure this value higher. For example, the sql used by 100validationQuery to check whether the connection is valid or not is required to be a query statement, which is commonly used as select'x'. If validationQuery is null,testOnBorrow, testOnReturn, testWhileIdle will not work. ValidationQueryTimeout unit: second, the timeout to check whether the connection is valid. When the underlying layer calls the void setQueryTimeout (int seconds) method testOnBorrowtrue of the jdbc Statement object to apply for a connection, validationQuery is performed to check whether the connection is valid. This configuration will degrade performance. When testOnReturnfalse returns the connection, validationQuery is performed to check whether the connection is valid, and this configuration degrades performance. TestWhileIdlefalse recommends that you configure it as true, which does not affect performance and ensures security. When applying for a connection, it is tested that if the idle time is greater than timeBetweenEvictionRunsMillis, validationQuery is performed to check whether the connection is valid. KeepAlivefalse

(1.0.28) for connections within the number of minIdle in the connection pool, if the idle time exceeds minEvictableIdleTimeMillis, the keepAlive operation will be performed. TimeBetweenEvictionRunsMillis1 minutes (1.0.14) have two meanings:

1) the Destroy thread detects the interval between connections and closes the physical connection if the idle time of the connection is greater than or equal to minEvictableIdleTimeMillis.

2) the judgment basis of testWhileIdle, take a detailed look at the description of testWhileIdle attribute numTestsPerEvictionRun30 minute (1.0.14) is no longer used. A DruidDataSource only supports an EvictionRunminEvictableIdleTimeMillis connection to remain idle without being expelled. The sqlexceptionSorter executed during the initialization of a connectionInitSqls physical connection is automatically identified according to dbType when the database throws some unrecoverable exceptions. When the database throws some unrecoverable exceptions, the filters attribute type of the discarded connection is a string, and the extension is configured by aliases. Common plug-ins are:

Filter:stat for monitoring and statistics

Filter:log4j for logging

The filter:wallproxyFilters type to defend against sql injection is List. If both filters and proxyFilters are configured, it is a combination relationship, not a substitution relationship. 2. Use 2.1, use 2.1.1 directly, introduce dependency com.alibaba druid 1.2.82.1.2, use example package com.abc.demo.general.dbpool;import com.alibaba.druid.pool.DruidDataSource;import java.sql.Connection;import java.sql.ResultSet;import java.sql.SQLException;import java.sql.Statement Public class DruidCase {public static void main (String [] args) {DruidDataSource druidDataSource = new DruidDataSource (); Connection connection = null; try {druidDataSource.setName ("test connection pool"); druidDataSource.setDriverClassName ("com.mysql.cj.jdbc.Driver"); druidDataSource.setUrl ("jdbc:mysql://10.40.9.11:3306/mydb?useUnicode=true&characterEncoding=UTF-8") DruidDataSource.setUsername ("root"); druidDataSource.setPassword ("123456"); druidDataSource.setInitialSize (2); druidDataSource.setMinIdle (2); druidDataSource.setMaxActive (5); druidDataSource.setValidationQuery ("select 1"); druidDataSource.setTestWhileIdle (true); druidDataSource.setTestOnBorrow (true); druidDataSource.setTestOnReturn (false) DruidDataSource.setMaxWait (6000); druidDataSource.setFilters ("slf4j"); connection = druidDataSource.getConnection (); Statement st = connection.createStatement (); ResultSet rs = st.executeQuery ("select version ()"); if (rs.next ()) {System.out.println (rs.getString (1)) }} catch (SQLException e) {e.printStackTrace ();} finally {close (connection);} / / in practice, the data source is initialized when the application starts, and the application acquires a connection from the data source. The data source is not closed. DruidDataSource.close ();} private static void close (Connection connection) {if (connection! = null) {try {connection.close ();} catch (SQLException e) {e.printStackTrace () Using 2.1.1 in SpringBoot, Introduce dependent org.springframework.boot spring-boot-starter-parent 2.3.12.RELEASE org.springframework.boot spring-boot-starter-web org.springframework spring-jdbc com.alibaba druid-spring-boot-starter 1.2.8 mysql mysql-connector-java 2.1.2, single data source

Application.yml configuration:

Spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://10.40.9.11:3306/mydb?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 type: com.alibaba.druid.pool.DruidDataSource druid: initial-size: 2 min-idle: 2 max-active: 5 validation-query: select 1 test-while-idle: true test-on-borrow: true Test-on-return: false max-wait: 6000 filter: slf4j

Use:

@ Autowiredprivate DataSource dataSource;2.1.3, multiple data sources

Application.yml configuration:

Spring: datasource: druid: db1: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://10.140.9.11:3306/mydb?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 initial-size: 2 min-idle: 2 max-active: 5 validation-query: select 1 test-while-idle: true test -on-borrow: true test-on-return: false max-wait: 6000 filter: slf4j db2: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://10.40.9.12:3306/mydb?useUnicode=true&characterEncoding=UTF-8 username: root password: 123456 initial-size: 2 min-idle: 2 max-active: 5 Validation-query: select 1 test-while-idle: true test-on-borrow: true test-on-return: false max-wait: 6000 filter: slf4j

Data source configuration class:

Package com.abc.demo.config;import com.alibaba.druid.spring.boot.autoconfigure.DruidDataSourceBuilder;import org.springframework.boot.context.properties.ConfigurationProperties;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;import org.springframework.context.annotation.Primary;import javax.sql.DataSource @ Configurationpublic class DataSourceConfig {@ Primary @ Bean ("dataSource1") @ ConfigurationProperties ("spring.datasource.druid.db1") public DataSource dataSourceOne () {return DruidDataSourceBuilder.create () .build ();} @ Bean ("dataSource2") @ ConfigurationProperties ("spring.datasource.druid.db2") public DataSource dataSourceTwo () {return DruidDataSourceBuilder.create () .build ();}}

Use:

@ Autowired@Qualifier ("dataSource1") private DataSource dataSource1;@Autowired@Qualifier ("dataSource2") private DataSource dataSource2;2.1.4, enable monitoring function

Druid has some built-in monitoring, which can be enabled with a small amount of configuration in Spring Boot environment.

Application.yml configuration:

Spring: datasource: driver-class-name: com.mysql.cj.jdbc.Driver url: jdbc:mysql://10.40.9.11:3306/mydb?useUnicode=true&characterEncoding=UTF-8 username: root password: InsYR0ot187! Type: com.alibaba.druid.pool.DruidDataSource druid: initial-size: 2 min-idle: 2 max-active: 5 validation-query: select 1 test-while-idle: true test-on-borrow: true test-on-return: false max-wait: 6000 filter: slf4j,stat Wall # enable logging, monitoring statistics, firewall functions web-stat-filter: # web monitoring configuration enabled: true stat-view-servlet: # monitoring page configuration enabled: true url-pattern: / druid/*

Monitoring page:

At this point, the study on "what are the configuration parameters of Java database connection pool Druid" is over. I hope to be able to solve your doubts. The collocation of theory and practice can better help you learn, go and try it! If you want to continue to learn more related knowledge, please continue to follow the website, the editor will continue to work hard to bring you more practical articles!

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report