連接池深入分析

一二驰、模擬連接池

1、目的:連接池產(chǎn)品的復(fù)用機制如何設(shè)計的

2矿酵、連接池類--FastConnectionPool

3坏瘩、創(chuàng)建一個數(shù)據(jù)庫連接池--LinkedList

4漠魏、初始10個連接對象--循環(huán)添加10個連接對象

5柱锹、來一個客戶端禁熏,從連接池里取--(取出并移除連接池對象)

6、當(dāng)客戶用完了胧华,則不是真的銷毀矩动,而是放入到連接池中

FastConnectPool.java

/**

* 1. 創(chuàng)建一個數(shù)據(jù)庫連接池

2. 初始10個連接對象---放入集合(池)

3. 來一個客戶端悲没,從連接池里取

4. 當(dāng)客戶用完了男图,則不是真的銷毀逊笆,而是放入到連接池中

*

*/

public class FastConnectPool {

//1. 創(chuàng)建一個數(shù)據(jù)庫連接池

//2. 初始10個連接對象---放入集合(池)

//使用LinkedList难裆,調(diào)用它內(nèi)部派生的方法

public static LinkedList<Connection> list = new LinkedList<>();

static{

for(int i=0;i<10;i++){

list.add(DBUtils.getConnection());

}

}

public Connection getConnection(){

//1.要判斷池子中是否有連接對象;沒有則重新創(chuàng)建連接池

//2.判斷是否超出了最大連接數(shù)據(jù)

//3.判斷是否超時

return list.removeFirst(); //拿到元素,并從集合中移除

}

public void release(Connection conn) {

list.addLast(conn);? //在集合后面追加

}

}

Test.java

/**

* 模擬連接池的操作:

*

*/

public class Test {

public static void main(String[] args) {

FastConnectPool pool = new FastConnectPool();

System.out.println(FastConnectPool.list.size());? //10

Connection conn = pool.getConnection();

System.out.println(FastConnectPool.list.size()); //9

//如何回收

pool.release(conn);

System.out.println(FastConnectPool.list.size()); //10

//說明: 為什么需要建立DataSource的標(biāo)準(zhǔn)偏化?

//方便更換連接池,做擴展及維護

/*DbcpPool pool2 = new DbcpPool();

pool2.getConn();

pool2.closeAll();*/

}

}

二驶冒、建立DataSource標(biāo)準(zhǔn)

1骗污、為什么需要建立標(biāo)準(zhǔn)

1)因為不同的連接池有不同實現(xiàn)需忿,不方便管理

2)換連接池產(chǎn)品時蜡歹,變動太大

2月而、如何建立標(biāo)準(zhǔn)的

1)新建連接池類(FastConnectionPool)實現(xiàn)DataSource接口

2)獲取連接對象時父款,獲取的是包裝類的連接對象

3)關(guān)閉時,進行了連接對象的回收

3世杀、為什么包裝連接對象可以回收到連接池

1)獲取連接對象時玫坛,返回包裝連接對象包晰,用接口接收沒問題

2)包裝類對象關(guān)閉連接時伐憾,其內(nèi)部是通過Connection對象去回收的

ConnectionWrapper.java

public class ConnectionWrapper implements Connection {

private LinkedList<Connection> list;

private Connection conn;

public ConnectionWrapper(LinkedList<Connection> list, Connection conn) {

this.conn = conn;

this.list = list;

}

@Override

public <T> T unwrap(Class<T> iface) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public boolean isWrapperFor(Class<?> iface) throws SQLException {

// TODO Auto-generated method stub

return false;

}

@Override

public Statement createStatement() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public PreparedStatement prepareStatement(String sql) throws SQLException {

return conn.prepareStatement(sql);

}

@Override

public CallableStatement prepareCall(String sql) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public String nativeSQL(String sql) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public void setAutoCommit(boolean autoCommit) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public boolean getAutoCommit() throws SQLException {

// TODO Auto-generated method stub

return false;

}

@Override

public void commit() throws SQLException {

// TODO Auto-generated method stub

}

@Override

public void rollback() throws SQLException {

// TODO Auto-generated method stub

}

@Override

public void close() throws SQLException {

//在此處寫成回收即可

System.out.println("回收.....");

list.addLast(conn);? //在集合后面追加

}

@Override

public boolean isClosed() throws SQLException {

// TODO Auto-generated method stub

return false;

}

@Override

public DatabaseMetaData getMetaData() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public void setReadOnly(boolean readOnly) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public boolean isReadOnly() throws SQLException {

// TODO Auto-generated method stub

return false;

}

@Override

public void setCatalog(String catalog) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public String getCatalog() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public void setTransactionIsolation(int level) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public int getTransactionIsolation() throws SQLException {

// TODO Auto-generated method stub

return 0;

}

@Override

public SQLWarning getWarnings() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public void clearWarnings() throws SQLException {

// TODO Auto-generated method stub

}

@Override

public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)

throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public Map<String, Class<?>> getTypeMap() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public void setTypeMap(Map<String, Class<?>> map) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public void setHoldability(int holdability) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public int getHoldability() throws SQLException {

// TODO Auto-generated method stub

return 0;

}

@Override

public Savepoint setSavepoint() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public Savepoint setSavepoint(String name) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public void rollback(Savepoint savepoint) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public void releaseSavepoint(Savepoint savepoint) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability)

throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency,

int resultSetHoldability) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency,

int resultSetHoldability) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public Clob createClob() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public Blob createBlob() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public NClob createNClob() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public SQLXML createSQLXML() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public boolean isValid(int timeout) throws SQLException {

// TODO Auto-generated method stub

return false;

}

@Override

public void setClientInfo(String name, String value) throws SQLClientInfoException {

// TODO Auto-generated method stub

}

@Override

public void setClientInfo(Properties properties) throws SQLClientInfoException {

// TODO Auto-generated method stub

}

@Override

public String getClientInfo(String name) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public Properties getClientInfo() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public Array createArrayOf(String typeName, Object[] elements) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public Struct createStruct(String typeName, Object[] attributes) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public void setSchema(String schema) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public String getSchema() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public void abort(Executor executor) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public int getNetworkTimeout() throws SQLException {

// TODO Auto-generated method stub

return 0;

}

}

FastConnectPool.java

/**

* 1. 創(chuàng)建一個數(shù)據(jù)庫連接池

2. 初始10個連接對象---放入集合(池)

3. 來一個客戶端乡话,從連接池里取

4. 當(dāng)客戶用完了,則不是真的銷毀诬像,而是放入到連接池中

*

*/

public class FastConnectPool implements DataSource {

//1. 創(chuàng)建一個數(shù)據(jù)庫連接池

//2. 初始10個連接對象---放入集合(池)

//使用LinkedList坏挠,調(diào)用它內(nèi)部派生的方法

private static LinkedList<Connection> list = new LinkedList<>();

static{

for(int i=0;i<10;i++){

list.add(DBUtils.getConnection());

}

}

public Connection getConnection(){

//1.要判斷池子中是否有連接對象邪乍;沒有則重新創(chuàng)建連接池

//2.判斷是否超出了最大連接數(shù)據(jù)

//3.判斷是否超時

Connection conn = list.removeFirst();

//設(shè)計模式: 裝飾者模式

//包裝后得到更強大的類庇楞,最終的實現(xiàn)依然是原生對象去處理的

ConnectionWrapper wrapper = new ConnectionWrapper(list,conn);

return wrapper; //拿到元素姐刁,并從集合中移除

}

@Override

public PrintWriter getLogWriter() throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public void setLogWriter(PrintWriter out) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public void setLoginTimeout(int seconds) throws SQLException {

// TODO Auto-generated method stub

}

@Override

public int getLoginTimeout() throws SQLException {

// TODO Auto-generated method stub

return 0;

}

@Override

public Logger getParentLogger() throws SQLFeatureNotSupportedException {

// TODO Auto-generated method stub

return null;

}

@Override

public <T> T unwrap(Class<T> iface) throws SQLException {

// TODO Auto-generated method stub

return null;

}

@Override

public boolean isWrapperFor(Class<?> iface) throws SQLException {

// TODO Auto-generated method stub

return false;

}

@Override

public Connection getConnection(String username, String password) throws SQLException {

// TODO Auto-generated method stub

return null;

}

}

Test.java

/**

* 建立DataSouce標(biāo)準(zhǔn):

* 1.自定義的連接池產(chǎn)品要實現(xiàn)DataSouce

* 2.在獲取連接對象時壁拉,返回的是包裝類的連接對象--(就是Connection的實現(xiàn)類對象)

* 3.在連接的包裝類中重寫close方法--回收

*

*/

public class Test {

public static void main(String[] args) throws SQLException {

DataSource dataSource = new FastConnectPool();

Connection conn = dataSource.getConnection();

//dataSource.release();? err 實現(xiàn)類派生的方法不能調(diào)用

//((FastConnectPool)dataSource).release();? //不能強轉(zhuǎn)柏靶,強轉(zhuǎn)后就不是面向接口了

PreparedStatement prst = conn.prepareStatement("insert into t_user(name,password) values('uu','123')");

int result = prst.executeUpdate();

System.out.println(result);

conn.close();? //直接會關(guān)閉連接對象--->本質(zhì)變回收

}

}

?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末痘昌,一起剝皮案震驚了整個濱河市炬转,隨后出現(xiàn)的幾起案子扼劈,更是在濱河造成了極大的恐慌,老刑警劉巖骑冗,帶你破解...
    沈念sama閱讀 222,590評論 6 517
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件贼涩,死亡現(xiàn)場離奇詭異遥倦,居然都是意外死亡,警方通過查閱死者的電腦和手機闷供,發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 95,157評論 3 399
  • 文/潘曉璐 我一進店門,熙熙樓的掌柜王于貴愁眉苦臉地迎上來粮呢,“玉大人钞艇,你說我怎么就攤上這事哩照。” “怎么了识藤?”我有些...
    開封第一講書人閱讀 169,301評論 0 362
  • 文/不壞的土叔 我叫張陵痴昧,是天一觀的道長冠王。 經(jīng)常有香客問我,道長柱彻,這世上最難降的妖魔是什么豪娜? 我笑而不...
    開封第一講書人閱讀 60,078評論 1 300
  • 正文 為了忘掉前任,我火速辦了婚禮哟楷,結(jié)果婚禮上侵歇,老公的妹妹穿的比我還像新娘。我一直安慰自己吓蘑,他們只是感情好惕虑,可當(dāng)我...
    茶點故事閱讀 69,082評論 6 398
  • 文/花漫 我一把揭開白布坟冲。 她就那樣靜靜地躺著,像睡著了一般健提。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上伟叛,一...
    開封第一講書人閱讀 52,682評論 1 312
  • 那天私痹,我揣著相機與錄音,去河邊找鬼统刮。 笑死紊遵,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的侥蒙。 我是一名探鬼主播暗膜,決...
    沈念sama閱讀 41,155評論 3 422
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼鞭衩!你這毒婦竟也來了学搜?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 40,098評論 0 277
  • 序言:老撾萬榮一對情侶失蹤论衍,失蹤者是張志新(化名)和其女友劉穎瑞佩,沒想到半個月后,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體坯台,經(jīng)...
    沈念sama閱讀 46,638評論 1 319
  • 正文 獨居荒郊野嶺守林人離奇死亡炬丸,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 38,701評論 3 342
  • 正文 我和宋清朗相戀三年,在試婚紗的時候發(fā)現(xiàn)自己被綠了蜒蕾。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片稠炬。...
    茶點故事閱讀 40,852評論 1 353
  • 序言:一個原本活蹦亂跳的男人離奇死亡,死狀恐怖滥搭,靈堂內(nèi)的尸體忽然破棺而出酸纲,到底是詐尸還是另有隱情,我是刑警寧澤瑟匆,帶...
    沈念sama閱讀 36,520評論 5 351
  • 正文 年R本政府宣布闽坡,位于F島的核電站,受9級特大地震影響愁溜,放射性物質(zhì)發(fā)生泄漏疾嗅。R本人自食惡果不足惜,卻給世界環(huán)境...
    茶點故事閱讀 42,181評論 3 335
  • 文/蒙蒙 一冕象、第九天 我趴在偏房一處隱蔽的房頂上張望代承。 院中可真熱鬧,春花似錦渐扮、人聲如沸论悴。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,674評論 0 25
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽膀估。三九已至幔亥,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間察纯,已是汗流浹背帕棉。 一陣腳步聲響...
    開封第一講書人閱讀 33,788評論 1 274
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機就差點兒被人妖公主榨干…… 1. 我叫王不留饼记,地道東北人香伴。 一個月前我還...
    沈念sama閱讀 49,279評論 3 379
  • 正文 我出身青樓,卻偏偏與公主長得像具则,于是被迫代替她去往敵國和親即纲。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,851評論 2 361

推薦閱讀更多精彩內(nèi)容