第三十四章 創建鏈接池來實現鏈接的複用


使用鏈接池來獲取鏈接

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);
	}
	
	
}



發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章