当前位置:网站首页>Simple implementation of database connection pool

Simple implementation of database connection pool

2022-07-01 05:29:00 lanleihhh

The configuration file

driver=com.mysql.cj.jdbc.Driver
url=jdbc:mysql://127.0.0.1:3306/ssm?characterEncoding=utf8&useSSL=false&serverTimezone=Asia/Shanghai
uname=root
pwd=lanlei6843

Set profile database.properties Put it in src Under the table of contents , take src Of Project Structure It is amended as follows Resource; You can go through properties.load Loaded in

Connection pool parameters

package com.ffyc.writepool.connectionpool;

import java.io.IOException;
import java.util.Properties;

/** *  Some parameters in connection pool  */
public class ConnectionPoolParam {
    
    private String driver;// Database driven 
    private String url;// Of the database to connect to url
    private String user;//DB user name 
    private String password;//DB password 
    private int minConnectionNum;// Minimum connections 
    private int maxConnectionNum;// maximum connection 
    private long maxFreeTime;// Maximum connection idle time 
    private long maxWaitTime;// Get the maximum wait time for the connection 
    private int autoIncrementConnNum = 5;// Automatically increase the number of connections 

    public ConnectionPoolParam() {
    
        Properties properties = new Properties();
        try {
    
            properties.load(this.getClass().getClassLoader().getResourceAsStream("database.properties"));
        } catch (IOException e) {
    
            throw new RuntimeException(e);
        }
        this.driver = properties.getProperty("driver");
        this.url = properties.getProperty("url");
        this.user = properties.getProperty("uname");
        this.password = properties.getProperty("pwd");
    }

    public String getDriver() {
    
        return driver;
    }

    public void setDriver(String driver) {
    
        this.driver = driver;
    }

    public String getUrl() {
    
        return url;
    }

    public void setUrl(String url) {
    
        this.url = url;
    }

    public String getUser() {
    
        return user;
    }

    public void setUser(String user) {
    
        this.user = user;
    }

    public String getPassword() {
    
        return password;
    }

    public void setPassword(String password) {
    
        this.password = password;
    }

    public int getMinConnectionNum() {
    
        return minConnectionNum;
    }

    public void setMinConnectionNum(int minConnectionNum) {
    
        this.minConnectionNum = minConnectionNum;
    }

    public int getMaxConnectionNum() {
    
        return maxConnectionNum;
    }

    public void setMaxConnectionNum(int maxConnectionNum) {
    
        this.maxConnectionNum = maxConnectionNum;
    }

    public long getMaxFreeTime() {
    
        return maxFreeTime;
    }

    public void setMaxFreeTime(long maxFreeTime) {
    
        this.maxFreeTime = maxFreeTime;
    }

    public long getMaxWaitTime() {
    
        return maxWaitTime;
    }

    public void setMaxWaitTime(long maxWaitTime) {
    
        this.maxWaitTime = maxWaitTime;
    }

    public int getAutoIncrementConnNum() {
    
        return autoIncrementConnNum;
    }

    public void setAutoIncrementConnNum(int autoIncrementConnNum) {
    
        this.autoIncrementConnNum = autoIncrementConnNum;
    }

    @Override
    public String toString() {
    
        return "ConnectionPoolParam{" +
                "driver='" + driver + '\'' +
                ", url='" + url + '\'' +
                ", user='" + user + '\'' +
                ", password='" + password + '\'' +
                ", minConnectionNum=" + minConnectionNum +
                ", maxConnectionNum=" + maxConnectionNum +
                ", maxFreeTime=" + maxFreeTime +
                ", maxWaitTime=" + maxWaitTime +
                '}';
    }
}

Connection objects in the connection pool

package com.ffyc.writepool.connectionpool;

import java.sql.Connection;

/** *  Pooled connections  *  Connections in the database connection pool  *  contain   Connect   And   Using a state   Two attributes  */
public class PooledConnection {
    
    // Database connection 
    private Connection connection;

    // Is it used 
    private boolean isUsed;

    // Construct a pooled connection object 
    public PooledConnection(Connection connection) {
    
        this.connection = connection;
    }

    public Connection getConnection() {
    
        return connection;
    }

    public void setConnection(Connection connection) {
    
        this.connection = connection;
    }

    public boolean isUsed() {
    
        return isUsed;
    }

    public void setUsed(boolean used) {
    
        isUsed = used;
    }
}

Connection pool

package com.ffyc.writepool.connectionpool;

import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Iterator;
import java.util.concurrent.CopyOnWriteArrayList;


public class ConnectionPool {
    
    private ConnectionPoolParam param;// Parameters in the connection pool 

    private CopyOnWriteArrayList<PooledConnection> connections;// A collection of connections stored in the connection pool 

    /** *  Construct a connection pool with specified parameters  * @param param  Connection pool parameter object  */
    public ConnectionPool(ConnectionPoolParam param) {
    
        this.param = param;
    }

    // Get connection pool parameters 
    public ConnectionPoolParam getParam() {
    
        return param;
    }

    // Set connection pool parameters 
    public void setParam(ConnectionPoolParam param) {
    
        this.param = param;
    }

    // Create a database connection pool 
    public synchronized void createPool() throws ClassNotFoundException, SQLException {
    
        // If it has already been created , We won't create 
        if(connections != null){
    
            return;
        }

        System.out.println("param:" + param);

        // The load driver 
        Class.forName(this.getParam().getDriver());
        // Create a collection to hold the connections in the connection pool 
        connections = new CopyOnWriteArrayList<>();
        // Create a specified number of connections 
        createConnection(this.getParam().getMinConnectionNum());
        System.out.println(" Connection pool created successfully !");
    }

    /** *  establish  minConnectionNum  Connect , Put these connections into the connection pool ( aggregate ) connections in  * @param minConnectionNum  Minimum connections  */
    private void createConnection(int minConnectionNum)  {
    
        for (int i = 0; i < minConnectionNum; i++) {
    
            // Current connections   achieve   maximum connection   Exit to create 
            if(this.param.getMaxConnectionNum() > 0 && this.connections.size() >= this.param.getMaxConnectionNum()){
    
                break;
            }
            // Add a new   Pooled connection   Into the connection pool 
            try {
    
                connections.add(new PooledConnection(newConnection()));
            } catch (SQLException e) {
    
                System.out.println("  Failed to create database connection ! " + e.getMessage());
                throw new RuntimeException(e);
            }
            System.out.println(" Database connection Connection  Created !");
        }
    }

    /** *  Create a new connection , And back to  * @return  Newly created database connection  */
    private Connection newConnection() throws SQLException {
    
        // Create a new database connection 
        Connection connection = DriverManager.getConnection(this.param.getUrl(), this.param.getUser(), this.param.getPassword());
        //
        if(connections.size() == 0){
    
            DatabaseMetaData metaData = connection.getMetaData();
            int dbMaxConnections = metaData.getMaxConnections();

            //dbMaxConnections=0  Indicates that the database has no maximum connection limit   or   Cannot get the maximum connection limit 
            // If the database has a maximum connection limit 
            if(dbMaxConnections > 0){
    
                // If the maximum number of connections in the connection pool  >  The maximum number of connections allowed by the database 
                if(this.param.getMaxConnectionNum() > dbMaxConnections){
    
                    // The maximum number of connections to the connection pool   Set as   The maximum number of connections allowed by the database 
                    this.param.setMaxConnectionNum(dbMaxConnections);
                }
            }
        }
        return connection;
    }

    /** *  Return an idle database connection  *  If there is no free connection , And you cannot create a new connection   Just wait synchronously  * @return  Return an idle connection  */
    public synchronized Connection getConnection() throws SQLException, InterruptedException {
    

        System.out.print(" Getting connection -->");

        // If the connection pool has not been created , Unable to get connection 
        if(connections == null){
    
            return null;
        }

        // Get an idle connection 
        Connection connection = getFreeConnection();

        while (connection == null){
    
            Thread.sleep(1000);
            // Try it again , Until an idle connection is obtained 
            connection = getFreeConnection();
        }
        return connection;
    }

    /** *  Get an idle connection from the pool , *  If all connections in pool are used , return null * @return  Return idle connections  */
    private Connection getFreeConnection() throws SQLException {
    
        System.out.print(" Getting idle connections -->");

        // Get an idle connection 
        Connection connection = findFreeConnection();
        // If there are no free connections in the connection pool 
        if(connection == null){
    
            // Create some connections ( once 5 individual , If the maximum number of connections has been reached , No more creation )
            createConnection(this.param.getAutoIncrementConnNum());
            // After creation , Again, check whether there is an idle connection 
            connection = findFreeConnection();
            // There is still no free connection , return null
            if(connection == null){
    
                return null;
            }
        }
        return connection;// Return the idle connection obtained 
    }

    /** *  Find free connections in the pool , No return found null * @return  Return idle connections  */
    private Connection findFreeConnection() {
    
        System.out.println(" Looking for free connections ...");

        Connection connection = null;
        PooledConnection pooledConnection = null;
        // Get all in the collection   Pooled connection 
        Iterator<PooledConnection> iterator = connections.iterator();
        while (iterator.hasNext()){
    
            pooledConnection = iterator.next();
            // If the pooled connection is not used 
            if(!pooledConnection.isUsed()){
    
                // Get the connection 
                connection = pooledConnection.getConnection();
                // Set the connection status to used 
                pooledConnection.setUsed(true);
                // Found an idle connection , sign out 
                break;
            }
        }
        return connection;
    }

    /** *  Return a connection object to the connection pool , Set to idle  * * @param conn  The connection object to return  */
    public void returnConnection(Connection connection){
    
        // Connection pool does not exist , Can't return 
        if(connections == null){
    
            throw new IllegalArgumentException(" Connection pool has not been created , Unable to return connection to connection pool !");
        }

        PooledConnection pooledConnection = null;
        Iterator<PooledConnection> iterator = connections.iterator();
        // Traverse all connections in the connection pool , Find the connection to return 
        while (iterator.hasNext()){
    
            pooledConnection = iterator.next();
            if(connection == pooledConnection.getConnection()){
    
                // Find the connection , Set the status to idle 
                pooledConnection.setUsed(false);
                break;
            }
        }
    }

    /** *  Refresh the connection objects in the connection pool  */
    public synchronized void refreshConnection() throws InterruptedException, SQLException {
    
        if(connections == null){
    
            throw new IllegalArgumentException(" Connection pool not created , Can't refresh !");
        }

        PooledConnection pooledConnection = null;
        Iterator<PooledConnection> iterator = connections.iterator();
        while (iterator.hasNext()){
    
            // Get the objects in the pool 
            pooledConnection = iterator.next();
            // If the connection is being used , wait for 10s Refresh again 
            if(pooledConnection.isUsed()){
    
                Thread.sleep(10000);
            }

            //1. Close the connection 
            closeConnection(pooledConnection.getConnection());
            //2. Use a new connection instead of 
            pooledConnection.setConnection(newConnection());
            //3. Set the new connection status to   Free 
            pooledConnection.setUsed(false);
        }
    }

    /** *  Close a specified connection  * @param connection */
    private void closeConnection(Connection connection) {
    
        try {
    
            connection.close();
        } catch (SQLException e) {
    
            throw new IllegalArgumentException("  Error closing database connection : " + e.getMessage());
        }
    }

    /** *  Close the connection , Empty connection pool  */
    public synchronized void closeConnectionPool() throws InterruptedException {
    
        if(connections == null){
    
            throw new IllegalArgumentException(" Connection pool does not exist , Unable to close !");
        }

        PooledConnection pooledConnection = null;
        Iterator<PooledConnection> iterator = connections.iterator();
        while (iterator.hasNext()){
    
            pooledConnection = iterator.next();
            // If the current connection is in use , wait for 10s And then it's shut down 
            if(pooledConnection.isUsed()){
    
                Thread.sleep(10000);
            }
            // Close the current connection 
            closeConnection(pooledConnection.getConnection());
            // Delete the current connection from the pool 
            connections.remove(pooledConnection);
        }
        // Empty connection pool 
        connections = null;
    }
}

test

package com.ffyc.writepool.test;

import com.ffyc.writepool.connectionpool.ConnectionPool;
import com.ffyc.writepool.connectionpool.ConnectionPoolParam;

import java.sql.Connection;
import java.sql.SQLException;

public class TestConnectionPool {
    
    public static void main(String[] args) throws Exception {
    
        ConnectionPoolParam param = new ConnectionPoolParam();
        param.setMaxConnectionNum(20);// maximum connection 
        param.setMinConnectionNum(5);// Minimum connections 
        param.setAutoIncrementConnNum(5);// The number of new connections each time 
        param.setMaxFreeTime(60);// Maximum free time 60s
        param.setMaxWaitTime(5);// The longest waiting time 

        //1. Construct database connection pool 
        ConnectionPool pool = new ConnectionPool(param);
        //2. Get database connection 
        Connection connection = pool.getConnection();
        //3. Create connection pool 
        pool.createPool();

        // Get the connection 
        Connection[] connections = new Connection[21];
        for (int i = 0; i < connections.length; i++) {
    
            connections[i] = pool.getConnection();
            System.out.println(i+1+":"+connections[i]);
        }
    }
}

First create the connection object with the minimum number of connections (5 individual )
 Insert picture description here
 Insert picture description here
 Insert picture description here

原网站

版权声明
本文为[lanleihhh]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/182/202207010522235029.html