単純なデータベース接続プール

単純なデータベース接続プール

インポートのjava.sql.Connection;
インポートのjava.sql.DriverManager。
輸入ます。java.sql.SQLException;
輸入java.util.LinkedList;
輸入はjava.util.ResourceBundle;

@Component
パブリッククラスJdbcUtils {

private static String greenplum_driver;
private static String greenplum_url;
private static String greenplum_user;
private static String greenplum_password;
private LinkedList<Connection> dataSources=new LinkedList<Connection>();


static {
    greenplum_driver = ResourceBundle.getBundle("gpDb").getString("greenplum_driver");
    greenplum_url = ResourceBundle.getBundle("gpDb").getString("greenplum_url");
    greenplum_user = ResourceBundle.getBundle("gpDb").getString("greenplum_user");
    greenplum_password = ResourceBundle.getBundle("gpDb").getString("greenplum_password");
}


public  JdbcUtils() {
    try {
        //加载驱动
        Class.forName(greenplum_driver);
        //装载驱动
        //循环创建5个连接并放入连接池
        for (int i = 0; i < 10; i++) {
            Connection con = DriverManager.getConnection(greenplum_url, greenplum_user, greenplum_password);
            dataSources.add(con);
        }
    } catch (ClassNotFoundException e) {
        e.printStackTrace();
    } catch (SQLException e) {
        e.printStackTrace();
    }

}
//取出连接池中一个连接

public Connection getConnection() throws SQLException {
    Connection conn=null;
    if(dataSources.size()>0){
        conn = dataSources.removeFirst(); // 删除第一个连接返回
    }else{
        Connection con = DriverManager.getConnection(greenplum_url, greenplum_user, greenplum_password);
        conn =con;
    }
    return conn;
}

//将连接放回连接池
public void releaseConnection(Connection conn) {
    if(dataSources.size()<10) {
        dataSources.add(conn);
    }else{
        try {
            conn.close();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}

}

リリース元の4件の記事 ウォンの賞賛1 ビュー123

おすすめ

転載: blog.csdn.net/chaouyany/article/details/105054980