第三十四章リンクプールを作成してリンクの多重化を実現する
リンクプールを使用してリンクを取得
接続の取得と解除
接続プール
public static void main(String[] args) throws SQLException{
for(int i=0;i<20;i++){
Connection conn = JdbcUtilsPool.getConnection();
System.out.println(conn);
JdbcUtilsPool.free(null, null, conn);
}
}
接続の取得と解除
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
/**
* Connection
* @author Administrator
*
*/
public class JdbcUtilsPool {
private static MyDataSource myDataSource = null;
private JdbcUtilsPool(){
}
static{
try {
Class.forName("com.mysql.jdbc.Driver");
myDataSource = new MyDataSource();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
/* , */
public static Connection getConnection() throws SQLException{
return myDataSource.getConnection();
}
public static void free(ResultSet rs, Statement st, Connection conn){
if(rs!=null){
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(st!=null){
try {
st.close();
} catch (SQLException e) {
e.printStackTrace();
}finally{
if(conn != null){
//conn.close();
myDataSource.free(conn); // ,
}
}
}
}
}
}
}
接続プール
package cn.itcast.jdbc;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList;
public class MyDataSource {
private LinkedList<Connection> connectionsPool = new LinkedList<Connection>(); //
private static String username = "mysqlroot";
private static String password = "mysqlroot";
private static String url = "jdbc:mysql://localhost:3306/db_cityinfo";
private static int initCount = 5; //
private static int maxCount = 10; //
private static int currentCount = 0; //
/* */
public MyDataSource(){
for(int i=0; i<initCount; i++){
try {
this.connectionsPool.addLast(this.createConnection()); //
this.currentCount++;
} catch (SQLException e) {
throw new ExceptionInInitializerError(e);
}
}
}
/* */
public Connection getConnection() throws SQLException{
synchronized (connectionsPool) { //
if(this.connectionsPool.size() > 0){ // , ,
return this.connectionsPool.removeFirst();
}
if(this.currentCount < maxCount){ // , ,
this.currentCount++;
return this.createConnection();
}
throw new SQLException(" "); // ,
}
}
/* , */
public void free(Connection conn){
this.connectionsPool.addLast(conn);
}
/* */
private Connection createConnection() throws SQLException{
return DriverManager.getConnection(url,username,password);
}
}