search
HomeDatabaseMysql TutorialTomcat-dbcp database connection pool configuration and some pitfalls when using it

1. Database connection pool

When developing, you often need to perform some operations on the database, such as common additions, deletions, modifications, and searches. When the amount of data is small, It can be operated directly, but when the amount of data increases, each connection and release of the database will take a certain amount of time. At this time, the database connection pool can be used to maintain the database link and reduce the overhead caused by connecting to the database on the program, and It can reduce the pressure on the database, so what is the database connection pool? As the name suggests, it is a pond. What is placed in the pond is a link to the database. For example, a fish pond is a pond for raising fish. If you want to eat fish, you can directly fish it. You don’t have to buy fry and raise fish yourself. The database The connection pool is used to store links to the database. All links are established uniformly. When used, you can directly take them from it. After use, you can put them back into the pool. Since you use this thing, then We don’t need to write the code ourselves. Some open source ones can be used directly. There are three common open source connection pools, c3p0, dbcp, and proxool. I have never used c3p0 and proxool, just simple I have used dbcp pool, here I will talk about how to use dbcp database connection pool, and some pitfalls encountered when using it

Figure 1, before using connection pool



Figure 2 After using the connection pool

As shown in Figure 1 above, before using the connection pool, you need to A link is established to the database every time and needs to be released at any time. When the amount of data is large, it requires a lot of overhead to connect to the database, and frequent access and release of the database will also put a lot of pressure on the database. , Figure 2 shows that after using the database connection pool, all links are placed in the pool without releasing them. When used, they are taken directly from the pool and put back into the pool after use. The pool maintains long links to the database. If the link is disconnected, it will automatically reconnect. If the connection is not enough, subsequent users will need to wait.

2. Use the jar package used by tomcat-dbcp

contains tomcat-dbcp.jar That’s it, the rest are some basic packages

3. Configuration used

dbname.Driver=com.mysql.jdbc.Driver
dbname.Url=jdbc:mysql://<your ip>/<your dbname>?useUnicode=true&characterEncoding=UTF-8
&autoReconnect=true&failOverReadOnly=false&maxReconnects=10&autoReconnectForPools=true&zeroDateTimeBehavior=convertToNull&connectTimeout=3000
dbname.Username=<your username>
dbname.Password=<your password>
dbname.InitialSize=15
dbname.MinIdle=10
dbname.MaxIdle=20
dbname.MaxWait=5000
dbname.MaxActive=20
dbname.validationQuery=select 1

These configurations only need to be placed in .properties, about each The meaning


where driver, url, username, and password are common database connection configurations


InitialSize为初始化建立的连接数
minidle为数据库连接池中保持的最少的空闲的链接数
maxidle数据库连接池中保持的最大的连接数
maxwait等待数据库连接池分配连接的最长时间,超出之后报错
maxactivite最大的活动链接数,如果是多线程可以设置为超出多线程个数个链接数
<pre name="code" class="java">validationQuery测试是否连接是有效的sql语句

3. Connection pool code

public abstract class DB {

    private static HashMap<String, DataSource> dsTable = new HashMap<String, DataSource>();//此处记得用static
    private BasicDataSource ds;
    private PreparedStatement stmt = null;

    private DataSource getDataSource(String n) {
        if (dsTable.containsKey(n)) {
            return dsTable.get(n);//如果不同的数据库,多个连接池
        } else {
        	synchronized (dsTable) {
        		ds = new BasicDataSource();
                ds.setDriverClassName(DBConfig.getString("db", n.concat(".Driver")));//将<yourname>.properties的值读进来
                ds.setUrl(DBConfig.getString("db", n.concat(".Url")));
                ds.setUsername(DBConfig.getString("db", n.concat(".Username")));
                ds.setPassword(DBConfig.getString("db", n.concat(".Password")));
                ds.setInitialSize(DBConfig.getInteger("db", n.concat(".InitialSize")));
                ds.setMinIdle(DBConfig.getInteger("db", n.concat(".MinIdle")));
                ds.setMaxIdle(DBConfig.getInteger("db", n.concat(".MaxIdle")));
                ds.setMaxWait(DBConfig.getInteger("db", n.concat(".MaxWait")));
                ds.setMaxActive(DBConfig.getInteger("db", n.concat(".MaxActive")));
                ds.setValidationQuery(DBConfig.getString("db", n.concat(".validationQuery")));
                dsTable.put(n, ds);

                return ds;
			}
        }
    }

    protected Connection conn;

    public boolean open() throws SQLException {
    	BasicDataSource bds=(BasicDataSource)this.getDataSource(this.getConnectionName());
    	System.out.println("connection_number:"+bds.getNumActive()+"dsTable:"+dsTable);
        this.conn = this.getDataSource(this.getConnectionName()).getConnection();
        return true;
    }

    public void close() throws SQLException {
    	
        if (this.conn != null)
            this.conn.close();
    }

    protected abstract String getConnectionName();//此函数可以根据自己的需求,将数据库的名字传进来即可

    public void prepareStatement(String sql) throws SQLException {
        this.stmt = this.conn.prepareStatement(sql);
    }

    public void setObject(int index, Object value, int type) throws SQLException {
        this.stmt.setObject(index, value, type);
    }

    public void setObject(int index, Object value) throws SQLException {
        this.stmt.setObject(index, value);
    }

    public int execute() throws SQLException {
        return this.stmt.executeUpdate();
    }
}

The above is the code used when using the thread pool. It only gives a rough writing method. The specific DBDAO part needs to be implemented by yourself according to your own needs, such as batch processing, query, and update. Functions such as these can be modified according to personal needs, so how do you judge whether the link you create is what you want? There are two ways to check

1. Create an empty database and check the number of links

2. Check the number of links under linux

Get the processid

ps aux|grep <your java name>

View the links to the database

netstat -apn|grep <your processid>

You can see the specific number of links to check whether your connection pool is correct


4. Some pitfalls encountered

Because it is used in multi-threaded form, the most important pitfall encountered is the usage of static. Because I am not too familiar with it, I don’t use static. , resulting in each thread establishing a database connection pool, and a "too many files open" error occurred. This was caused by the fact that static was not used in the thread pool.

The above is the tomcat-dbcp database connection pool configuration and some pitfalls when using it. For more related content, please pay attention to the PHP Chinese website (www.php.cn)!


Statement
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Explain the InnoDB Buffer Pool and its importance for performance.Explain the InnoDB Buffer Pool and its importance for performance.Apr 19, 2025 am 12:24 AM

InnoDBBufferPool reduces disk I/O by caching data and indexing pages, improving database performance. Its working principle includes: 1. Data reading: Read data from BufferPool; 2. Data writing: After modifying the data, write to BufferPool and refresh it to disk regularly; 3. Cache management: Use the LRU algorithm to manage cache pages; 4. Reading mechanism: Load adjacent data pages in advance. By sizing the BufferPool and using multiple instances, database performance can be optimized.

MySQL vs. Other Programming Languages: A ComparisonMySQL vs. Other Programming Languages: A ComparisonApr 19, 2025 am 12:22 AM

Compared with other programming languages, MySQL is mainly used to store and manage data, while other languages ​​such as Python, Java, and C are used for logical processing and application development. MySQL is known for its high performance, scalability and cross-platform support, suitable for data management needs, while other languages ​​have advantages in their respective fields such as data analytics, enterprise applications, and system programming.

Learning MySQL: A Step-by-Step Guide for New UsersLearning MySQL: A Step-by-Step Guide for New UsersApr 19, 2025 am 12:19 AM

MySQL is worth learning because it is a powerful open source database management system suitable for data storage, management and analysis. 1) MySQL is a relational database that uses SQL to operate data and is suitable for structured data management. 2) The SQL language is the key to interacting with MySQL and supports CRUD operations. 3) The working principle of MySQL includes client/server architecture, storage engine and query optimizer. 4) Basic usage includes creating databases and tables, and advanced usage involves joining tables using JOIN. 5) Common errors include syntax errors and permission issues, and debugging skills include checking syntax and using EXPLAIN commands. 6) Performance optimization involves the use of indexes, optimization of SQL statements and regular maintenance of databases.

MySQL: Essential Skills for Beginners to MasterMySQL: Essential Skills for Beginners to MasterApr 18, 2025 am 12:24 AM

MySQL is suitable for beginners to learn database skills. 1. Install MySQL server and client tools. 2. Understand basic SQL queries, such as SELECT. 3. Master data operations: create tables, insert, update, and delete data. 4. Learn advanced skills: subquery and window functions. 5. Debugging and optimization: Check syntax, use indexes, avoid SELECT*, and use LIMIT.

MySQL: Structured Data and Relational DatabasesMySQL: Structured Data and Relational DatabasesApr 18, 2025 am 12:22 AM

MySQL efficiently manages structured data through table structure and SQL query, and implements inter-table relationships through foreign keys. 1. Define the data format and type when creating a table. 2. Use foreign keys to establish relationships between tables. 3. Improve performance through indexing and query optimization. 4. Regularly backup and monitor databases to ensure data security and performance optimization.

MySQL: Key Features and Capabilities ExplainedMySQL: Key Features and Capabilities ExplainedApr 18, 2025 am 12:17 AM

MySQL is an open source relational database management system that is widely used in Web development. Its key features include: 1. Supports multiple storage engines, such as InnoDB and MyISAM, suitable for different scenarios; 2. Provides master-slave replication functions to facilitate load balancing and data backup; 3. Improve query efficiency through query optimization and index use.

The Purpose of SQL: Interacting with MySQL DatabasesThe Purpose of SQL: Interacting with MySQL DatabasesApr 18, 2025 am 12:12 AM

SQL is used to interact with MySQL database to realize data addition, deletion, modification, inspection and database design. 1) SQL performs data operations through SELECT, INSERT, UPDATE, DELETE statements; 2) Use CREATE, ALTER, DROP statements for database design and management; 3) Complex queries and data analysis are implemented through SQL to improve business decision-making efficiency.

MySQL for Beginners: Getting Started with Database ManagementMySQL for Beginners: Getting Started with Database ManagementApr 18, 2025 am 12:10 AM

The basic operations of MySQL include creating databases, tables, and using SQL to perform CRUD operations on data. 1. Create a database: CREATEDATABASEmy_first_db; 2. Create a table: CREATETABLEbooks(idINTAUTO_INCREMENTPRIMARYKEY, titleVARCHAR(100)NOTNULL, authorVARCHAR(100)NOTNULL, published_yearINT); 3. Insert data: INSERTINTObooks(title, author, published_year)VA

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

Powerful PHP integrated development environment

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)