gjfer 发表于 2015-07-09 11:05

最简单的数据库连接池

[代码]代码package com.jxva.dao;

import java.io.PrintWriter;
import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.Date;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.ConcurrentMap;
import java.util.concurrent.Semaphore;

import javax.sql.DataSource;

import com.jxva.log.Logger;
import com.jxva.util.RandomUtil;

public class SimpleDataSource implements DataSource{

    private String driverClass;
    private String url;
    private String username;
    private String password;
    private int minSize;
    private int maxSize;

    private static final Logger log = Logger.getLogger(SimpleDataSource.class);
    private static final ConcurrentMap<Connection, Date> pool = new ConcurrentHashMap<Connection, Date>();
    private Semaphore semaphore;
   
    public SimpleDataSource() {
      minSize = 1;
      maxSize = 5;
      log.debug("Database Connection Pool initializing...");
    }

   
    public void close(Connection conn) throws SQLException {
      try{
            synchronized (pool) {               
                if (pool.size() < maxSize) {
                  pool.put(conn,new Date());
                  return;
                }
            }
            conn.close();
      }finally{
            semaphore.release();
      }
    }

    public void destroy() throws SQLException {
      for (Connection conn : pool.keySet()) {
            conn.close();
      }
      pool.clear();
    }

    @Override
    public Connection getConnection() throws SQLException {
      try {
            semaphore.acquire();
      } catch (InterruptedException e1) {
            //ignore
      }
      synchronized (pool) {
            if (!pool.isEmpty()) {
                //Connection conn = pool.keySet().iterator().next();// fetch last connection for ever
               Connection conn=(Connection)pool.keySet().toArray(); //random fetch one connection
                pool.remove(conn);
                try {
                  conn.setAutoCommit(true);
                } catch (SQLException e) {
                  pool.clear();
                  conn = getConnection();
                }
                return getProxyConnection(conn);
            }
      }
      //System.out.println(url);
      //System.out.println(username+":"+password);
      //return DriverManager.getConnection("jdbc:mysql://10.204.79.234:3306/library?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8",username,password);
         
      //url = "jdbc:mysql://10.204.79.234:3306/library?zeroDateTimeBehavior=convertToNull&useUnicode=true&characterEncoding=utf-8";
      return getProxyConnection(DriverManager.getConnection(url,username,password));
    }

    private Connection getProxyConnection(Connection connection) {
      final Connection conn = connection;
      InvocationHandler handler = new InvocationHandler() {
            public Object invoke(Object proxy, Method method, Object[] params) throws Exception {
                Object ret = null;
                if ("close".equals(method.getName())) {
                  close(conn);
                } else {
                  ret = method.invoke(conn, params);
                }
                return ret;
            }
      };
      return (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(), new Class[] { Connection.class }, handler);
    }

    public String getUrl() {
      return url;
    }

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

    public String getUsername() {
      return username;
    }

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

    public String getPassword() {
      return password;
    }

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

    public int getMinSize() {
      return minSize;
    }

    public void setMinSize(int minSize) {
      this.minSize = minSize;
    }

    public int getMaxSize() {
      return maxSize;
    }

    public void setMaxSize(int maxSize) {
      semaphore=new Semaphore(maxSize,false);
      this.maxSize = maxSize;
    }

    public String getDriverClass() {
      return driverClass;
    }

    public void setDriverClass(String driverClass) {
      try {
            Class.forName(driverClass);
      } catch (ClassNotFoundException e) {
            log.error(driverClass+" not exists.");
            throw new DataSourceException(driverClass+" not exists.",e);
      }
      this.driverClass = driverClass;
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public int getLoginTimeout() throws SQLException {
      // TODO Auto-generated method stub
      return 0;
    }

    @Override
    public java.util.logging.Logger getParentLogger()
            throws SQLFeatureNotSupportedException {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public void setLogWriter(PrintWriter arg0) throws SQLException {
      // TODO Auto-generated method stub
         
    }

    @Override
    public void setLoginTimeout(int arg0) throws SQLException {
      // TODO Auto-generated method stub
         
    }

    @Override
    public boolean isWrapperFor(Class<?> arg0) throws SQLException {
      // TODO Auto-generated method stub
      return false;
    }

    @Override
    public <T> T unwrap(Class<T> arg0) throws SQLException {
      // TODO Auto-generated method stub
      return null;
    }

    @Override
    public Connection getConnection(String arg0, String arg1)
            throws SQLException {
      // TODO Auto-generated method stub
      return null;
    }
}
页: [1]
查看完整版本: 最简单的数据库连接池