手寫數據庫連接池

  1.  相信很多人看這篇文章已經知道連接池是用來幹什麼的?沒錯,數據庫連接池就是爲數據庫連接建立一個“緩衝池”,預先在“緩衝池”中放入一定數量的連接欸,當需要建立數據庫連接時,從“緩衝池”中取出一個,使用完畢後再放進去。這樣的好處是,可以避免頻繁的進行數據庫連接佔用很多的系統資源。

  

  2.  常見的數據庫連接池有:dbcp,c3p0,阿里的Druid。好了,閒話不多說,本篇文章旨在加深大家對連接池的理解。這裏我選用的數據庫是mysql。

  

  3.  先講講連接池的流程:


  1. 首先要有一份配置文件吧!我們在日常的項目中使用數據源時,需要配置數據庫驅動,數據庫用戶名,數據庫密碼,連接。這四個角色萬萬不可以少。

相信很多人看這篇文章已經知道連接池是用來幹什麼的?沒錯,數據庫連接池就是爲數據庫連接建立一個“緩衝池”,預先在“緩衝池”中放入一定數量的連接欸,當需要建立數據庫連接時,從“緩衝池”中取出一個,使用完畢後再放進去。這樣的好處是,可以避免頻繁的進行數據庫連接佔用很多的系統資源。
常見的數據庫連接池有:dbcp,c3p0,阿里的Druid。好了,閒話不多說,本篇文章旨在加深大家對連接池的理解。這裏我選用的數據庫是mysql。
先講講連接池的流程:
首先要有一份配置文件吧!我們在日常的項目中使用數據源時,需要配置數據庫驅動,數據庫用戶名,數據庫密碼,連接。這四個角色萬萬不可以少。


#文件名:db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=lfdy
jdbc.initSize=3
jdbc.maxSize=10
#是否啓動檢查
jdbc.health=true
#檢查延遲時間
jdbc.delay=3000
#間隔時間
jdbc.period=3000
jdbc.timeout=100000


2. 我們要根據上述的配置文件db.properties編寫一個類,並加載其屬性


public class GPConfig {
    private String driver;
    private String url;
    private String username;
    private String password;
    private String initSize;
    private String maxSize;
    private String health;
    private String delay;
    private String period;
    private String timeout;

  //省略set和get方法//編寫構造器,在構造器中對屬性進行初始化
    public GPConfig() {
        Properties prop = new Properties();
        //maven項目中讀取文件好像只有這中方式
        InputStream stream = this.getClass().getResourceAsStream("/resource/db.properties");
        try {
            prop.load(stream);
            //在構造器中調用setter方法,這裏屬性比較多,我們肯定不是一步一步的調用,建議使用反射機制
            for(Object obj : prop.keySet()){
                //獲取形參,怎麼獲取呢?這不就是配置文件的key去掉,去掉什麼呢?去掉"jdbc."
                String fieldName = obj.toString().replace("jdbc.", "");
                Field field = this.getClass().getDeclaredField(fieldName);
                Method method = this.getClass().getMethod(toUpper(fieldName), field.getType());
                method.invoke(this, prop.get(obj));
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
   
    //讀取配置文件中的key,並把他轉成正確的set方法
    public String toUpper(String fieldName){
        char[] chars = fieldName.toCharArray();
        chars[0] -=32;    //如何把一個字符串的首字母變成大寫
        return "set"+ new String(chars);
    }
}


3.好了,我們配置文件寫好了,加載配置文件的類也寫好了,接下來寫什麼呢?回憶一下,我們在沒有連接池前,是不是用Class.forName(),getConnection等等來連接數據庫的?所以,我們接下來編寫一個類,這個類中有創建連接,獲取連接的方法。


public class GPPoolDataSource {
   
    //加載配置類
    GPConfig config = new GPConfig();
   
    //寫一個參數,用來標記當前有多少個活躍的連接
    private AtomicInteger currentActive = new AtomicInteger(0);
   
    //創建一個集合,幹嘛的呢?用來存放連接,畢竟我們剛剛初始化的時候就需要創建initSize個連接
    //並且,當我們釋放連接的時候,我們就把連接放到這裏面
    Vector<Connection> freePools = new Vector<>();
   
    //正在使用的連接池
    Vector<GPPoolEntry> usePools = new Vector<>();
   
    //構造器中初始化
    public GPPoolDataSource(){
        init();
    }

    //初始化方法
    public void init(){
        try {
            //我們的jdbc是不是每次都要加載呢?肯定不是的,只要加載一次就夠了
            Class.forName(config.getDriver());
            for(int i = 0; i < Integer.valueOf(config.getInitSize());i++){
                Connection conn = createConn();
                freePools.add(conn);
            }
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        }
        check();
    }
   
    //創建連接
    public synchronized Connection createConn(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
            currentActive.incrementAndGet();
            System.out.println("創建一個連接, 當前的活躍的連接數目爲:"+ currentActive.get()+" 連接:"+conn);
           
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * 創建連接有了,是不是也應該獲取連接呢?
     * @return
     */
    public synchronized GPPoolEntry getConn(){
        Connection conn = null;
        if(!freePools.isEmpty()){
            conn = freePools.get(0);
            freePools.remove(0);
        }else{
            if(currentActive.get() < Integer.valueOf(config.getMaxSize())){
                conn = createConn();
            }else{
                try {
                    System.out.println("連接池已經滿了,需要等待...");
                    wait(1000);
                    return getConn();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        GPPoolEntry poolEntry = new GPPoolEntry(conn, System.currentTimeMillis());
        //獲取連接幹嘛的?不就是使用的嗎?所以,每獲取一個,就放入正在使用池中
        usePools.add(poolEntry);
        return poolEntry;
    }
   
   
    /**
     * 創建連接,獲取連接都已經有了,接下來就是該釋放連接了
     */
    public synchronized void release(Connection conn){
        try {
            if(!conn.isClosed() && conn != null){
                freePools.add(conn);
            }
            System.out.println("回收了一個連接,當前空閒連接數爲:"+freePools.size());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
   
    //定時檢查佔用時間超長的連接,並關閉
    private void check(){
        if(Boolean.valueOf(config.getHealth())){
            Worker worker = new Worker();
            new java.util.Timer().schedule(worker, Long.valueOf(config.getDelay()), Long.valueOf(config.getPeriod()));
        }
    }
   
    class Worker extends TimerTask{
        @Override
        public void run() {
            System.out.println("例行檢查...");
            for(int i = 0; i < usePools.size();i++){
                GPPoolEntry entry = usePools.get(i);
                long startTime = entry.getUseStartTime();
                long currentTime = System.currentTimeMillis();
                if((currentTime-startTime)>Long.valueOf(config.getTimeout())){
                    Connection conn = entry.getConn();
                    try {
                        if(conn != null && !conn.isClosed()){
                            conn.close();
                            usePools.remove(i);
                            currentActive.decrementAndGet();
                            System.out.println("發現有超時連接,強行關閉,當前活動的連接數:"+currentActive.get());
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}


4.在上述的check()方法中,要檢查是否超時,所以我們需要用一個包裝類


public class GPPoolEntry {
   
    private Connection conn;
    private long useStartTime;
    public Connection getConn() {
        return conn;
    }
    public void setConn(Connection conn) {
        this.conn = conn;
    }
    public long getUseStartTime() {
        return useStartTime;
    }
    public void setUseStartTime(long useStartTime) {
        this.useStartTime = useStartTime;
    }
   
    public GPPoolEntry(Connection conn, long useStartTime) {
        super();
        this.conn = conn;
        this.useStartTime = useStartTime;
    }
}


5.好了,萬事具備,我們寫一個測試類測試一下吧


public class GPDataSourceTest {

    public static void main(String[] args) {

        GPPoolDataSource dataSource = new GPPoolDataSource();

        Runnable runnable = () -> {
            Connection conn = dataSource.getConn().getConn();
            System.out.println(conn);
        };

        ExecutorService executorService = Executors.newFixedThreadPool(5);
        for (int i = 0; i < 60; i++) {
            executorService.submit(runnable);
        }
        executorService.shutdown();
    }

}


4.好了,我給下我的結果:


640?wx_fmt=png&wxfrom=5&wx_lazy=1

640?wx_fmt=png&wxfrom=5&wx_lazy=1

 5.總結下,這個手寫連接池部分,其實我也是學習的別人的,所以有很多東西不熟悉,也有許多漏洞,現在我先說下我需要完善的地方:


    • 反射機制

    • 讀取properties文件

    • 線程池

    • 線程

    • 集合Vector





640?wx_fmt=jpeg&wxfrom=5&wx_lazy=1


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章