资源池模式和单例模式实现的自定义数据库连接池java实现版

2019-12-20 12:51:53 浏览数 (1)

在企业级开发中,我们往往不会直接使用原生的JDBC操作来实现与数据库得连接。因为数据库的连接是一个很宝贵的资源且耗时,我们往往会在内存中引入一个资源池来统一管理数据库的连接。这个模式也被总结为一种设计模式:资源池模式和单例模式。 关于原理部分就不多做介绍了,这里也是做一个简单的原理实现。

ObjectPool连接池接口

代码语言:javascript复制
package com.test.pool;

import java.util.Enumeration;
import java.util.Hashtable;
import java.util.concurrent.ConcurrentHashMap;

public abstract class ObjectPool<T> {
      private long expirationTime;

      private Hashtable<T, Long> locked, unlocked;

      public ObjectPool() {
        expirationTime = 30000; // 30 seconds
        locked = new Hashtable<T, Long>();
        unlocked = new Hashtable<T, Long>();
      }

      protected abstract T create();

      public abstract boolean validate(T o);

      public abstract void expire(T o);

      public synchronized T checkOut() {
        long now = System.currentTimeMillis();
        T t;
        if (unlocked.size() > 0) {
          Enumeration<T> e = unlocked.keys();
          while (e.hasMoreElements()) {
            t = e.nextElement();
            if ((now - unlocked.get(t)) > expirationTime) {
              // object has expired
              unlocked.remove(t);
              expire(t);
              t = null;
            } else {
              if (validate(t)) {
                unlocked.remove(t);
                locked.put(t, now);
                return (t);
              } else {
                // object failed validation
                unlocked.remove(t);
                expire(t);
                t = null;
              }
            }
          }
        }
        // no objects available, create a new one
        t = create();
        locked.put(t, now);
        return (t);
      }

      public synchronized void checkIn(T t) {
        locked.remove(t);
        unlocked.put(t, System.currentTimeMillis());
      }
}

JDBCConnectionPool 连接池实现

代码语言:javascript复制
package com.test.pool;

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

public class JDBCConnectionPool extends ObjectPool<Connection> {

      private String driver, url, username, password;
      
      private JDBCConnectionPool() {
          
      }

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

      @Override
      protected Connection create() {
        try {
          return (DriverManager.getConnection(url, username, password));
        } catch (SQLException e) {
          e.printStackTrace();
          return (null);
        }
      }

      @Override
      public void expire(Connection o) {
        try {
          ((Connection) o).close();
        } catch (SQLException e) {
          e.printStackTrace();
        }
      }

      @Override
      public boolean validate(Connection o) {
        try {
          return (!((Connection) o).isClosed());
        } catch (SQLException e) {
          e.printStackTrace();
          return (false);
        }
      }

    public String getDsn() {
        return url;
    }

    public void setDsn(String dsn) {
        this.url = dsn;
    }

    public String getUsr() {
        return username;
    }

    public void setUsr(String usr) {
        this.username = usr;
    }

    public String getPwd() {
        return password;
    }

    public void setPwd(String pwd) {
        this.password = pwd;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }
    
    public void loadDriver() {
        try {
            Class.forName(driver);
        } catch (ClassNotFoundException e) {
        }
    }
      
    
      
}

Main测试

代码语言:javascript复制
package com.test.pool;

import java.sql.Connection;
import java.sql.SQLException;

public class Main {
      public static void main(String args[]) throws SQLException {

        JDBCConnectionPool pool = JDBCConnectionPool.getInstance();
        pool.setDriver("com.mysql.jdbc.Driver");
        pool.setDsn("jdbc:mysql://192.168.2.113:3306/jhbims?useSSL=false&useUnicode=true&characterEncoding=UTF-8&amp;autoReconnect=true");
        pool.setUsr("jhbims");
        pool.setPwd("jhbims");
        pool.loadDriver();

        // Get a connection:
        Connection con = pool.checkOut();
        System.out.println(con.isValid(0));
        
        pool.checkIn(con);
     
      }
    }

本文由博客一文多发平台 OpenWrite 发布!

0 人点赞