当前位置:Gxlcms > 数据库问题 > 瞎j8封装第二版之数据库连接池

瞎j8封装第二版之数据库连接池

时间:2021-07-01 10:21:17 帮助过:4人阅读

=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=UTF-8&useSSL=true jdbc.username=root jdbc.password=yck940522 #最小连接数 jdbc.minSize=3 #最大连接数 jdbc.maxSize=50 #初始化连接数 jdbc.initSize=5 #重试次数 jdbc.tryTimes=2 #延迟时间 jdbc.delay=1000 jdbc.maxActiveSize=100 jdbc.timeOut=1200000 jdbc.check = true jdbc.checkTime = 30000

配了那么多参数,很多都没用上。。唉,还是太菜;

package jdbc;

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

public class DataBase {
    private static String username;
    private static String password;
    private static String url;
    private static String driver;

    private static Integer minSize;
    private static Integer maxSize;
    private static Integer initSize;
    private static Integer maxActiveSize;
    private static Integer tryTimes;
    private static Long delay;
    private static Long timeOut;
    private static Boolean checked;
    private static Long checkTime;

    private static DataBase instance;

    private DataBase(){
        InputStream in = DataBase.class.getClassLoader().getResourceAsStream("jdbc.properties");
        Properties p = new Properties();
        try {
            p.load(in);
            username = p.getProperty("jdbc.username");
            password = p.getProperty("jdbc.password");
            url = p.getProperty("jdbc.url");
            driver = p.getProperty("jdbc.driver");
            minSize = Integer.valueOf(p.getProperty("jdbc.minSize","3"));
            maxSize = Integer.valueOf(p.getProperty("jdbc.maxSize","20"));
            initSize = Integer.valueOf(p.getProperty("jdbc.initSize","5"));
            maxActiveSize = Integer.valueOf(p.getProperty("jdbc.maxActiveSize","100"));
            tryTimes =Integer.valueOf(p.getProperty("jdbc.tryTimes","2"));
            delay = Long.valueOf(p.getProperty("jdbc.delay","1000"));
            timeOut = Long.valueOf(p.getProperty("jdbc.timeOut","1200000"));
            checked = Boolean.valueOf(p.getProperty("jdbc.check","false"));
            checkTime = Long.valueOf(p.getProperty("jdbc.checkTime","30000"));

        } catch (IOException e) {
            e.printStackTrace();
        }finally {
            if(in != null){
                try {
                    in.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }


    public static DataBase getInstance(){
        if(instance == null){
            synchronized (DataBase.class){
                if(instance == null){
                    instance = new DataBase();
                }
            }
        }
        return instance;
    }

    public  String getUsername() {
        return username;
    }

    public  String getPassword() {
        return password;
    }

    public  String getUrl() {
        return url;
    }

    public  String getDriver() {
        return driver;
    }

    public  Integer getMinSize() {
        return minSize;
    }

    public  Integer getMaxSize() {
        return maxSize;
    }

    public  Integer getInitSize() {
        return initSize;
    }

    public  Integer getMaxActiveSize() {
        return maxActiveSize;
    }

    public  Integer getTryTimes() {
        return tryTimes;
    }

    public  Long getDelay() {
        return delay;
    }

    public  Long getTimeOut() {
        return timeOut;
    }

    public Boolean getChecked() {
        return checked;
    }

    public Long getCheckTime() {
        return checkTime;
    }
}

对单例也不太懂,瞎写,有经验的大佬指正一下啊

package jdbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;
import java.util.Vector;
import java.util.concurrent.atomic.AtomicInteger;

public class ConnectionPool{

    private static final Long lazyTime = 30000L;

    private DataBase dataBase;
    private AtomicInteger totalSize = new AtomicInteger(0);
    private List<Connection> freeConnections = new Vector<Connection>();
    private ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();

    private static ConnectionPool  instance;

    private ConnectionPool(){
        this.dataBase = DataBase.getInstance();
        init();
    }

    public static ConnectionPool getInstance(){
        if(instance == null){
            synchronized (ConnectionPool.class){
                if(instance == null){
                    instance = new ConnectionPool();
                }
            }
        }
        return instance;
    }

    private void init(){
        try {
            Class.forName(dataBase.getDriver());
            for(int i=0;i<dataBase.getInitSize();i++){
                Connection connection = createConnection();
                freeConnections.add(connection);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
    }


    private synchronized Connection createConnection(){
        try {
            Class.forName(dataBase.getDriver());
            Connection conn= DriverManager.getConnection(dataBase.getUrl(),dataBase.getUsername(),dataBase.getPassword());
            totalSize.incrementAndGet();
            return conn;
        } catch (SQLException e) {
            e.printStackTrace();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        return null;
    }

    private synchronized Connection getConnection() {
        Connection conn= null;
        try {
            if(totalSize.get() < dataBase.getMaxSize()){
                if(freeConnections.size()>0){
                    conn = freeConnections.get(0);
                    if(conn != null){
                        threadLocal.set(conn);
                    }
                    freeConnections.remove(0);
                }else {
                    conn = createConnection();
                }
            }else {
                wait(dataBase.getDelay());
                conn = getConnection();
            }
        } catch (InterruptedException e) {
            e.printStackTrace();
        }

        return conn;
    }

    private boolean isValid(Connection conn){
        try {
            if(conn == null || conn.isClosed()){
                return false;
            }
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return true;
    }

    public synchronized Connection getCurrentConnection() {
        Connection conn = threadLocal.get();
        if(!isValid(conn)){
            return getConnection();
        }
        return conn;
    }

    public void checkPool() {
        if(dataBase.getChecked()){
            new Timer().schedule(new TimerTask() {
                @Override
                public void run() {
                    System.out.println("空线池连接数:"+freeConnections.size());
                    System.out.println("总的连接数:"+totalSize.get());
                }
            }, lazyTime, dataBase.getCheckTime());
        }
    }

}

这个连接池我就不做什么说明了。。。自己只能理解最简单的。。。简单的说就是先初始化一部分连接放在一个list里,要用的时候就去取,如果没有超过上限也不用close了。。但是我一直没搞明白怎么去判断它空闲了多长时间然后close掉。。。所以很多也没实现。

 

大王让我写代码 

2017-12-30

瞎j8封装第二版之数据库连接池

标签:nts   thread   log   cal   read   name   sys   cte   value   

人气教程排行