溫馨提示×

您好,登錄后才能下訂單哦!

密碼登錄×
登錄注冊(cè)×
其他方式登錄
點(diǎn)擊 登錄注冊(cè) 即表示同意《億速云用戶服務(wù)條款》

手寫數(shù)據(jù)庫連接池

發(fā)布時(shí)間:2020-07-01 01:59:01 來源:網(wǎng)絡(luò) 閱讀:859 作者:www19 欄目:數(shù)據(jù)庫

  1.  相信很多人看這篇文章已經(jīng)知道連接池是用來干什么的?沒錯(cuò),數(shù)據(jù)庫連接池就是為數(shù)據(jù)庫連接建立一個(gè)“緩沖池”,預(yù)先在“緩沖池”中放入一定數(shù)量的連接欸,當(dāng)需要建立數(shù)據(jù)庫連接時(shí),從“緩沖池”中取出一個(gè),使用完畢后再放進(jìn)去。這樣的好處是,可以避免頻繁的進(jìn)行數(shù)據(jù)庫連接占用很多的系統(tǒng)資源。

  

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

  

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


  1. 首先要有一份配置文件吧!我們?cè)谌粘5捻?xiàng)目中使用數(shù)據(jù)源時(shí),需要配置數(shù)據(jù)庫驅(qū)動(dòng),數(shù)據(jù)庫用戶名,數(shù)據(jù)庫密碼,連接。這四個(gè)角色萬萬不可以少。

相信很多人看這篇文章已經(jīng)知道連接池是用來干什么的?沒錯(cuò),數(shù)據(jù)庫連接池就是為數(shù)據(jù)庫連接建立一個(gè)“緩沖池”,預(yù)先在“緩沖池”中放入一定數(shù)量的連接欸,當(dāng)需要建立數(shù)據(jù)庫連接時(shí),從“緩沖池”中取出一個(gè),使用完畢后再放進(jìn)去。這樣的好處是,可以避免頻繁的進(jìn)行數(shù)據(jù)庫連接占用很多的系統(tǒng)資源。
常見的數(shù)據(jù)庫連接池有:dbcp,c3p0,阿里的Druid。好了,閑話不多說,本篇文章旨在加深大家對(duì)連接池的理解。這里我選用的數(shù)據(jù)庫是mysql。
先講講連接池的流程:
首先要有一份配置文件吧!我們?cè)谌粘5捻?xiàng)目中使用數(shù)據(jù)源時(shí),需要配置數(shù)據(jù)庫驅(qū)動(dòng),數(shù)據(jù)庫用戶名,數(shù)據(jù)庫密碼,連接。這四個(gè)角色萬萬不可以少。


#文件名: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
#是否啟動(dòng)檢查
jdbc.health=true
#檢查延遲時(shí)間
jdbc.delay=3000
#間隔時(shí)間
jdbc.period=3000
jdbc.timeout=100000


2. 我們要根據(jù)上述的配置文件db.properties編寫一個(gè)類,并加載其屬性


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方法//編寫構(gòu)造器,在構(gòu)造器中對(duì)屬性進(jìn)行初始化
    public GPConfig() {
        Properties prop = new Properties();
        //maven項(xiàng)目中讀取文件好像只有這中方式
        InputStream stream = this.getClass().getResourceAsStream("/resource/db.properties");
        try {
            prop.load(stream);
            //在構(gòu)造器中調(diào)用setter方法,這里屬性比較多,我們肯定不是一步一步的調(diào)用,建議使用反射機(jī)制
            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,并把他轉(zhuǎn)成正確的set方法
    public String toUpper(String fieldName){
        char[] chars = fieldName.toCharArray();
        chars[0] -=32;    //如何把一個(gè)字符串的首字母變成大寫
        return "set"+ new String(chars);
    }
}


3.好了,我們配置文件寫好了,加載配置文件的類也寫好了,接下來寫什么呢?回憶一下,我們?cè)跊]有連接池前,是不是用Class.forName(),getConnection等等來連接數(shù)據(jù)庫的?所以,我們接下來編寫一個(gè)類,這個(gè)類中有創(chuàng)建連接,獲取連接的方法。


public class GPPoolDataSource {
   
    //加載配置類
    GPConfig config = new GPConfig();
   
    //寫一個(gè)參數(shù),用來標(biāo)記當(dāng)前有多少個(gè)活躍的連接
    private AtomicInteger currentActive = new AtomicInteger(0);
   
    //創(chuàng)建一個(gè)集合,干嘛的呢?用來存放連接,畢竟我們剛剛初始化的時(shí)候就需要?jiǎng)?chuàng)建initSize個(gè)連接
    //并且,當(dāng)我們釋放連接的時(shí)候,我們就把連接放到這里面
    Vector<Connection> freePools = new Vector<>();
   
    //正在使用的連接池
    Vector<GPPoolEntry> usePools = new Vector<>();
   
    //構(gòu)造器中初始化
    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();
    }
   
    //創(chuàng)建連接
    public synchronized Connection createConn(){
        Connection conn = null;
        try {
            conn = DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
            currentActive.incrementAndGet();
            System.out.println("創(chuàng)建一個(gè)連接, 當(dāng)前的活躍的連接數(shù)目為:"+ currentActive.get()+" 連接:"+conn);
           
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }
    /**
     * 創(chuàng)建連接有了,是不是也應(yīng)該獲取連接呢?
     * @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("連接池已經(jīng)滿了,需要等待...");
                    wait(1000);
                    return getConn();
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        GPPoolEntry poolEntry = new GPPoolEntry(conn, System.currentTimeMillis());
        //獲取連接干嘛的?不就是使用的嗎?所以,每獲取一個(gè),就放入正在使用池中
        usePools.add(poolEntry);
        return poolEntry;
    }
   
   
    /**
     * 創(chuàng)建連接,獲取連接都已經(jīng)有了,接下來就是該釋放連接了
     */
    public synchronized void release(Connection conn){
        try {
            if(!conn.isClosed() && conn != null){
                freePools.add(conn);
            }
            System.out.println("回收了一個(gè)連接,當(dāng)前空閑連接數(shù)為:"+freePools.size());
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
   
    //定時(shí)檢查占用時(shí)間超長(zhǎng)的連接,并關(guān)閉
    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("發(fā)現(xiàn)有超時(shí)連接,強(qiáng)行關(guān)閉,當(dāng)前活動(dòng)的連接數(shù):"+currentActive.get());
                        }
                    } catch (SQLException e) {
                        e.printStackTrace();
                    }
                }
            }
        }
    }
}


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


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.好了,萬事具備,我們寫一個(gè)測(cè)試類測(cè)試一下吧


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.好了,我給下我的結(jié)果:


手寫數(shù)據(jù)庫連接池

手寫數(shù)據(jù)庫連接池

 5.總結(jié)下,這個(gè)手寫連接池部分,其實(shí)我也是學(xué)習(xí)的別人的,所以有很多東西不熟悉,也有許多漏洞,現(xiàn)在我先說下我需要完善的地方:


    • 反射機(jī)制

    • 讀取properties文件

    • 線程池

    • 線程

    • 集合Vector





手寫數(shù)據(jù)庫連接池


向AI問一下細(xì)節(jié)

免責(zé)聲明:本站發(fā)布的內(nèi)容(圖片、視頻和文字)以原創(chuàng)、轉(zhuǎn)載和分享為主,文章觀點(diǎn)不代表本網(wǎng)站立場(chǎng),如果涉及侵權(quán)請(qǐng)聯(lián)系站長(zhǎng)郵箱:is@yisu.com進(jìn)行舉報(bào),并提供相關(guān)證據(jù),一經(jīng)查實(shí),將立刻刪除涉嫌侵權(quán)內(nèi)容。

AI