自己写的数据库连接池

//已经应用,效率不错
package com.sunlei.DB.ConnectionPool;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Vector;

import com.sunlei.exceptions.CannotConnectToDBException;

/**
 * connection pool.
 * @author sunlei
 *
 */
public class DBConnectionPool{
    class ConnectionEntry{
        private Connection conn = null;
        private boolean isBusy = false;
        
        ConnectionEntry(){
            
        }
        ConnectionEntry(Connection conn){
            this(conn,false);
        }
        ConnectionEntry(Connection conn, boolean isBusy){
            this.conn = conn;
            this.isBusy = isBusy;
        }
        public void setConnection(Connection conn){
            this.conn = conn;
        }
        public Connection getConnection(){
            return this.conn;
        }
        
        public void setIsBusy(boolean isBusy){
            this.isBusy = isBusy;
        }
        public boolean getIsBusy(){
            return this.isBusy;
        }
    }

    private Vector<ConnectionEntry> connectionList = null;
    private int initConnectionNum = 0;
    private int maxConnectionNum = 0;
    private int increamentConnectionNum = 0;
    private String username = "";
    private String password = "";
    private String url = "";
    private String driver = "";
    
    public DBConnectionPool(){}
    
    public DBConnectionPool(String driver,String url,String username,String password,int initConnectionNum, int maxConnectionNum,int increamentConnectionNum){
        this.driver = driver;
        this.url = url;
        this.username = username;
        this.password = password;
        this.initConnectionNum = initConnectionNum;
        this.maxConnectionNum = maxConnectionNum;
        this.increamentConnectionNum = increamentConnectionNum;
        
        createPool();
    }
    
    private void createPool(){
        if(this.connectionList != null){
            return;
        }
        this.connectionList = new Vector<ConnectionEntry>();
        createConnection(this.initConnectionNum);
    }
    
    private void createConnection(int connectionNum){
        for(int i=0;i<connectionNum;i++){
            if(this.maxConnectionNum > 0 && this.connectionList.size() > this.maxConnectionNum){
                break;
            }
            Connection conn = newConnection();
            if(conn != null){
                this.connectionList.add(new ConnectionEntry(conn));
            }
        }
    }

    public synchronized Connection getConnection() throws CannotConnectToDBException{
        int atempCount = 0;
        Connection conn = getFreeConnection();
        
        while(conn == null){
            if(atempCount == 5){
                throw new CannotConnectToDBException();
            }
            try {
                Thread.sleep(250);
            } catch (InterruptedException e) {}
            conn = getFreeConnection();
            ++atempCount;
            System.out.println("already attemp: "+atempCount);
        }
        System.out.println("connect success begin!"+this.connectionList.size());
        return conn;
    }
    
    public synchronized void freeConnection(Connection conn){
        if(this.connectionList == null){
            return;
        }
        
        for(ConnectionEntry o : this.connectionList){
            if(o.getConnection() == conn){
                o.setIsBusy(false);
                break;
            }
        }
        System.out.println("connection close!"+this.connectionList.size());
    }
    
    public synchronized void refreshConnections(){
        if(this.connectionList != null){
            for(ConnectionEntry o : this.connectionList){
                if(o.isBusy){
                    try {
                        Thread.sleep(500);
                        this.closeConnection(o.getConnection());
                        o.setConnection(newConnection());
                        o.setIsBusy(false);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
    
    private void closeConnection(Connection conn){
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
    
    private Connection getFreeConnection(){
        Connection conn = findFreeConnection();
        
        if(conn == null){
            createConnection(this.increamentConnectionNum);
            conn = findFreeConnection();
            if(conn == null){
                conn = null;
            }
        }
        
        return conn;
    }
    
    private Connection findFreeConnection(){
        Connection conn = null;
        
        for(ConnectionEntry o : this.connectionList){
            if(!o.isBusy){
                conn = o.getConnection();
                o.setIsBusy(true);
                break;
            }
        }
        
        return conn;
    }
    
    private Connection newConnection(){
        Connection conn = null;
        try{
            Class.forName(driver);
            conn = DriverManager.getConnection(this.url, username, password);
            
            if(this.connectionList.size() == 0){
                int driverMaxConnectionNum = conn.getMetaData().getMaxConnections();
                if(driverMaxConnectionNum > 0 && this.maxConnectionNum > driverMaxConnectionNum){
                    this.maxConnectionNum = driverMaxConnectionNum;
                }
            }
        }catch(ClassNotFoundException e){
            e.printStackTrace();
        } catch (SQLException e) {}
        
        return conn;
    }
}
测试类:
package com.sunlei.client;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

import com.sunlei.DB.ConnectionPool.DBConnectionPool;
import com.sunlei.exceptions.CannotConnectToDBException;

public class ConnectionPoolTest {

    private final static String driver = "com.mysql.jdbc.Driver";
    private final static String url = "jdbc:mysql://localhost:3306/sunlei";
    private final static String username = "root";
    private final static String password = "sunlei";
    private static DBConnectionPool connectionPool = null;
   
    public static void main(String[] args) throws InterruptedException {
        connectionPool = new DBConnectionPool(driver,url,username,password,2,1000,1);
       
        for(int i=0;i<1000;i++){
            new Thread(){
                @Override
                public void run() {
                    try {
                        Connection conn = connectionPool.getConnection();
                        Statement statement = conn.createStatement();
                        ResultSet set = statement.executeQuery("select * from student limit 0,5");
                        Thread.sleep(10000);
                        connectionPool.freeConnection(conn);
                    } catch (CannotConnectToDBException e) {
                        System.out.println(e.getMessage());
                    } catch (SQLException e) {
                        e.printStackTrace();
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }.start();
            Thread.sleep(500);
        }
    }
}


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值