手写数据库连接池的实现

手写一个简单的数据库连接池:

Pool.java

package com.wxz.designpattern.factory.poolFactory;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.Driver;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

/**
 * Created by Administrator on 2019/3/17.
 */
public abstract class Pool {
    public String propertiesName="connection-INF.properties";
    private static Pool pool = null;
    protected int maxConnect=100;
    protected int normalConnect=10;
    protected String driverName=null;
    protected Driver driver=null;

    protected Pool(){
        try {
            init();
            loadDrivers(driverName);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void init() throws IOException {
        InputStream is=Pool.class.getResourceAsStream(propertiesName);
        Properties p=new Properties();
        p.load(is);
        this.driverName=p.getProperty("driverName");
        this.maxConnect=Integer.parseInt(p.getProperty("maxConnect"));
        this.normalConnect=Integer.parseInt(p.getProperty("normalConnect"));
    }

    protected void loadDrivers(String driverClassName){
        if(driverClassName==null || "".equals(driverClassName)){
            System.out.println("JDBC驱动程序为空,无法注册驱动程序");
        }
        try {
            driver = (Driver) Class.forName(driverClassName).newInstance();
            DriverManager.registerDriver(driver);
            System.out.println("注册JDBC驱动成功,驱动名称:"+driverClassName);
        } catch (Exception e) {
            System.out.println("注册JDBC驱动失败,驱动名称:"+driverClassName);
            e.printStackTrace();
        }
    }

    public abstract void createPool();

    public abstract Connection getConnection();

    public abstract Connection getConnection(long time);

    public static synchronized Pool getInstance() throws Exception{
        if(pool==null){
            pool=(Pool) Class.forName("org.e_book.sqlhelp.Pool").newInstance();
            if(pool!=null){
                pool.init();
            }
        }
        return pool;
    }

    public abstract void freeConnection(Connection connection);

    public abstract int getNum(); //获取空闲连接数

    public abstract int getActiveNum(); //获取活跃连接数

    protected synchronized void release(){
        try {
            DriverManager.deregisterDriver(driver);
            System.out.println("撤销JDBC驱动程序成功:"+driver.getClass().getName());
        } catch (SQLException e) {
            System.out.println("撤销JDBC驱动程序失败:"+driver.getClass().getName());
            e.printStackTrace();
        }
    }
}
DBConnectionPool.java
import java.io.InputStream;
import java.util.Date;
import java.util.Enumeration;
import java.util.Properties;
import java.util.Vector;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;

/**
 * Created by Administrator on 2019/3/17.
 */
public final class DBConnectionPool extends Pool{

    private int checkedOut; //正在使用的连接数

    private Vector<Connection> freeConnections=new Vector<Connection>();

    private String url=null;

    private String userName=null;

    private String password=null;

    private static int num=0;

    private static int activeNum=0;

    private static DBConnectionPool pool=null;

    public static synchronized DBConnectionPool getInstance(){
        if (pool==null){
            pool=new DBConnectionPool();
        }
        return pool;
    }

    private DBConnectionPool(){
        try {
            init();
            for(int i=0;i<normalConnect;i++){
                Connection c=newConnection();
                if(c!=null){
                    freeConnections.addElement(c);
                    num++; //记录连接总数
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    private void init() throws Exception {
        InputStream is=DBConnectionPool.class.getResourceAsStream(propertiesName);
        Properties p=new Properties();
        p.load(is);
        this.url=p.getProperty("url");
        this.userName=p.getProperty("userName");
        this.password=p.getProperty("password");
        this.driverName=p.getProperty("driverName");
        this.normalConnect=Integer.parseInt(p.getProperty("normalConnect"));
        this.maxConnect=Integer.parseInt(p.getProperty("maxConnect"));
    }

    private Connection newConnection(){
        Connection conn=null;
        try {
            if(userName !=null && password!=null){
                conn=DriverManager.getConnection(url,userName,password);
            }else{
                conn=DriverManager.getConnection(url);
            }
            System.out.println("连接池创建新的连接");
        } catch (SQLException e) {
            System.out.println("无法创建这个URL链接"+url);
            e.printStackTrace();
        }
        return conn;
    }

    public synchronized void freeConnection(Connection conn){
        freeConnections.addElement(conn);
        checkedOut--;
        activeNum++;
        notifyAll();
    }

    @Override
    public void createPool() {
        Pool pool=new DBConnectionPool();
        if(pool!=null){
            System.out.println("创建连接池成功");
        }else{
            System.out.println("创建连接池失败");
        }
    }

    @Override
    public Connection getConnection() {
        Connection conn=null;
        if(freeConnections.size()>0){
            num--;
            conn=freeConnections.firstElement();
            freeConnections.removeElementAt(0);
            try {
                if(conn!=null && conn.isClosed()){
                    conn=getConnection();
                }
            } catch (SQLException e) {
                conn=getConnection();
            }
        }else if(maxConnect==0 || checkedOut<maxConnect){
            conn=newConnection();
        }
        if(conn!=null){
            checkedOut++;
        }
        activeNum++;
        return conn;
    }

    @Override
    public Connection getConnection(long timeout) {
        long startTime=new Date().getTime();
        Connection conn=null;
        while((conn=getConnection())==null){
            try {
                wait(timeout);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
            if(new Date().getTime()-startTime>=timeout){
                return null;
            }
        }
        return conn;
    }

    //关闭所有连接
    public void realse(){
        try {
            Enumeration allConnections=freeConnections.elements();
            while(allConnections.hasMoreElements()){
                Connection conn=(Connection) allConnections.nextElement();
                try {
                    conn.close();
                    num--;
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            freeConnections.removeAllElements();
            activeNum=0;
        } finally {
            super.release();
        }
    }



    @Override
    public int getNum() {
        return num;
    }

    @Override
    public int getActiveNum() {
        return activeNum;
    }
}

 

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值