简单的数据库连接池示例

无主题博客 » 编程语言 » Java » 简单的数据库连接池示例

DatabasePool.java

package cn.wuzhuti.db;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;

public class DatabasePool {

    private final static Map<Connection, Boolean> connPool = new HashMap<Connection, Boolean>(); // 用来存放连接的“池”
    private final static int MINI_POOL_SIZE = 3;// 最小的连接数
    private final static int MAX_POOL_SIZE = 4;// 最大的连接数
    private static int currentConnNum = 0;// 当前连接数

    private static DatabasePool instance = new DatabasePool(); // 唯一实例

    /**
     * 构造方法,因为数据库连接池是个单例,所以不允许外界任意的new对象,构造方法设置为私有
     */
    private DatabasePool() {
        init();
    }

    /**
     * 获取这个实例的唯一方式
     * 
     * @return 唯一的池对象
     */
    public static DatabasePool getInstance() {
        return instance;
    }

    /**
     * 初始化连接池,在创建这个池实例时执行
     */
    private void init() {
        for (int i = 0; i < MINI_POOL_SIZE; i++) {
            connPool.put(createConnection(), true);
        }
    }

    /**
     * 创建连接对象,外界获取连接是从池里获取,该方法由类本身使用,所以该方法为私有
     * 
     * @return 数据库连接对象
     */
    private Connection createConnection() {
        Connection conn = null;
        try {
            Class.forName("com.mysql.jdbc.Driver");
        } catch (ClassNotFoundException e1) {
            e1.printStackTrace();
        }
        String url = "jdbc:mysql://127.0.0.1:3306/em?useUnicode=true&characterEncoding=UTF-8";
        try {
            conn = DriverManager.getConnection(url, "root", "");
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 外界获得一个数据库的连接
     * 
     * @return 数据库连接
     */
    public Connection getConnection() {
        Connection conn = null;
        if (currentConnNum < MINI_POOL_SIZE) {
            for (Connection con : connPool.keySet()) {
                if (connPool.get(con)) {
                    conn = con;
                    connPool.put(con, false);
                }
            }
            currentConnNum++;
            return conn;
        } else if (currentConnNum < MAX_POOL_SIZE) {
             conn = createConnection();
             connPool.put(conn, false);
             currentConnNum++;
             return conn;
         } else {
             return getConnection();
         }
    }
    /**
      * 当使用完连接后,要把连接放回池中,或者销毁连接并中池中移掉
      *
      * @param conn
      */
     public void close(Connection conn) {
         if (currentConnNum > MINI_POOL_SIZE) {
            try {
                conn.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } finally {
                connPool.remove(conn);
            }
        } else {
            connPool.put(conn, true);
        }

    }

    /**
     * @param args
     */
    public static void main(String[] args) {
        // TODO Auto-generated method stub

    }

}

TestDbPool.java

package cn.wuzhuti.db;

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;

public class TestDbPool {

    /**
     * @param args
     */
    public static void main(String[] args) {
        DatabasePool databasePool = DatabasePool.getInstance();
        Connection connection = databasePool.getConnection();
        try {
            Statement stat = connection.createStatement();
            String sql = "select * from jobs";
            ResultSet rs = stat.executeQuery(sql);
            while (rs.next()) {
                System.out.println(rs.getInt("id") + "  "
                        + rs.getString("name"));
            }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            // 需要关闭数据库连接,释放资源
        }
    }

}

发表评论

电子邮件地址不会被公开。 必填项已用*标注