本文實例講述了Java實現數據庫連接池的方法。分享給大家供大家參考。具體如下:
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
|
package com.kyo.connection; import java.sql.Connection; import java.sql.DatabaseMetaData; import java.sql.Driver; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.Statement; import java.util.Enumeration; import java.util.Vector; public class ConnectionPool { private ConnectionParam param; private String testTable = "" ; // 測試連接是否可用的測試表名,默認沒有測試表 private Vector connections = null ; // 存放連接池中數據庫連接的向量 , 初始時為 // null,它中存放的對象為PooledConnection 型 public void setParam(ConnectionParam param) { this .param = param; } public ConnectionParam getParam() { return param; } /** * 構造函數 * * @param param */ public ConnectionPool(ConnectionParam param) { this .param = param; } /** * * 獲取測試數據庫表的名字 * * @return 測試數據庫表的名字 */ public String getTestTable() { return this .testTable; } /** * * 設置測試表的名字 * * @param testTable * String 測試表的名字 */ public void setTestTable(String testTable) { this .testTable = testTable; } /** * 創建一個數據庫連接池,連接池中的可用連接的數量采用類成員 initialConnections 中設置的值 */ public synchronized void createPool() throws Exception { // 確保連接池沒有創建 // 如果連接池己經創建了,保存連接的向量 connections 不會為空 if (connections != null ) { return ; // 如果己經創建,則返回 } // 實例化 JDBC Driver 中指定的驅動類實例 Driver driver = (Driver) (Class.forName( this .param.getDriver()) .newInstance()); DriverManager.registerDriver(driver); // 注冊 JDBC 驅動程序 // 創建保存連接的向量 , 初始時有 0 個元素 connections = new Vector(); // 根據 initialConnections 中設置的值,創建連接。 createConnections( this .param.getMinConnection()); System.out.println( " 數據庫連接池創建成功! " ); } /** * * 創建由 numConnections 指定數目的數據庫連接 , 并把這些連接 放入 connections 向量中 * * @param numConnections * 要創建的數據庫連接的數目 */ private void createConnections( int numConnections) throws SQLException { // 循環創建指定數目的數據庫連接 for ( int x = 0 ; x < numConnections; x++) { // 是否連接池中的數據庫連接的數量己經達到最大?最大值由類成員 maxConnections,指出,如果 maxConnections // 為 0 或負數,表示連接數量沒有限制。 // 如果連接數己經達到最大,即退出。 if ( this .param.getMaxConnection() > 0 && this .connections.size() >= this .param.getMaxConnection()) { break ; } // add a new PooledConnection object to connections vector // 增加一個連接到連接池中(向量 connections 中) try { connections.addElement( new PooledConnection(newConnection())); } catch (SQLException e) { System.out.println( " 創建數據庫連接失敗! " + e.getMessage()); throw new SQLException(); } System.out.println( " 數據庫連接己創建 ......" ); } } /** * * 創建一個新的數據庫連接并返回它 * * @return 返回一個新創建的數據庫連接 */ private Connection newConnection() throws SQLException { // 創建一個數據庫連接 Connection conn = DriverManager.getConnection( this .param.getUrl(), this .param.getUser(), this .param.getPassword()); // 如果這是第一次創建數據庫連接,即檢查數據庫,獲得此數據庫允許支持的 // 最大客戶連接數目 // connections.size()==0 表示目前沒有連接己被創建 if (connections.size() == 0 ) { DatabaseMetaData metaData = conn.getMetaData(); int driverMaxConnections = metaData.getMaxConnections(); // 數據庫返回的 driverMaxConnections 若為 0 ,表示此數據庫沒有最大 // 連接限制,或數據庫的最大連接限制不知道 // driverMaxConnections 為返回的一個整數,表示此數據庫允許客戶連接的數 目 // 如果連接池中設置的最大連接數量大于數據庫允許的連接數目 , 則置連接池 的最大 // 連接數目為數據庫允許的最大數目 if (driverMaxConnections > 0 && this .param.getMaxConnection() > driverMaxConnections) { this .param.setMaxConnection(driverMaxConnections); } } return conn; // 返回創建的新的數據庫連接 } /** * * 通過調用 getFreeConnection() 函數返回一個可用的數據庫連接 , * * 如果當前沒有可用的數據庫連接,并且更多的數據庫連接不能創 * * 建(如連接池大小的限制),此函數等待一會再嘗試獲取。 * * @return 返回一個可用的數據庫連接對象 */ public synchronized Connection getConnection() throws SQLException { // 確保連接池己被創建 if (connections == null ) { return null ; // 連接池還沒創建,則返回 null } Connection conn = getFreeConnection(); // 獲得一個可用的數據庫連接 // 如果目前沒有可以使用的連接,即所有的連接都在使用中 while (conn == null ) { // 等一會再試 wait( 250 ); conn = getFreeConnection(); // 重新再試,直到獲得可用的連接,如果 // getFreeConnection() 返回的為 null // 則表明創建一批連接后也不可獲得可用連接 } return conn; // 返回獲得的可用的連接 } /** * * 本函數從連接池向量 connections 中返回一個可用的的數據庫連接,如果 * * 當前沒有可用的數據庫連接,本函數則根據 incrementalConnections 設置 * * 的值創建幾個數據庫連接,并放入連接池中。 * * 如果創建后,所有的連接仍都在使用中,則返回 null * * @return 返回一個可用的數據庫連接 */ private Connection getFreeConnection() throws SQLException { // 從連接池中獲得一個可用的數據庫連接 Connection conn = findFreeConnection(); if (conn == null ) { // 如果目前連接池中沒有可用的連接 // 創建一些連接 createConnections( this .param.getIncrementalConnections()); // 重新從池中查找是否有可用連接 conn = findFreeConnection(); if (conn == null ) { // 如果創建連接后仍獲得不到可用的連接,則返回 null return null ; } } return conn; } /** * * 查找連接池中所有的連接,查找一個可用的數據庫連接, * * 如果沒有可用的連接,返回 null * * @return 返回一個可用的數據庫連接 */ private Connection findFreeConnection() throws SQLException { Connection conn = null ; PooledConnection pConn = null ; // 獲得連接池向量中所有的對象 Enumeration enumerate = connections.elements(); // 遍歷所有的對象,看是否有可用的連接 while (enumerate.hasMoreElements()) { pConn = (PooledConnection) enumerate.nextElement(); if (!pConn.isBusy()) { // 如果此對象不忙,則獲得它的數據庫連接并把它設為忙 conn = pConn.getConnection(); pConn.setBusy( true ); // 測試此連接是否可用 if (!testConnection(conn)) { // 如果此連接不可再用了,則創建一個新的連接, // 并替換此不可用的連接對象,如果創建失敗,返回 null try { conn = newConnection(); } catch (SQLException e) { System.out.println( " 創建數據庫連接失敗! " + e.getMessage()); return null ; } pConn.setConnection(conn); } break ; // 己經找到一個可用的連接,退出 } } return conn; // 返回找到到的可用連接 } /** * * 測試一個連接是否可用,如果不可用,關掉它并返回 false * * 否則可用返回 true * * * * @param conn * 需要測試的數據庫連接 * * @return 返回 true 表示此連接可用, false 表示不可用 */ private boolean testConnection(Connection conn) { try { // 判斷測試表是否存在 if (testTable.equals( "" )) { // 如果測試表為空,試著使用此連接的 setAutoCommit() 方法 // 來判斷連接否可用(此方法只在部分數據庫可用,如果不可用 , // 拋出異常)。注意:使用測試表的方法更可靠 conn.setAutoCommit( true ); } else { // 有測試表的時候使用測試表測試 // check if this connection is valid Statement stmt = conn.createStatement(); stmt.execute( "select count(*) from " + testTable); } } catch (SQLException e) { // 上面拋出異常,此連接己不可用,關閉它,并返回 false; closeConnection(conn); return false ; } // 連接可用,返回 true return true ; } /** * * 此函數返回一個數據庫連接到連接池中,并把此連接置為空閑。 * * 所有使用連接池獲得的數據庫連接均應在不使用此連接時返回它。 * * @param 需返回到連接池中的連接對象 */ public void returnConnection(Connection conn) { // 確保連接池存在,如果連接沒有創建(不存在),直接返回 if (connections == null ) { System.out.println( " 連接池不存在,無法返回此連接到連接池中 !" ); return ; } PooledConnection pConn = null ; Enumeration enumerate = connections.elements(); // 遍歷連接池中的所有連接,找到這個要返回的連接對象 while (enumerate.hasMoreElements()) { pConn = (PooledConnection) enumerate.nextElement(); // 先找到連接池中的要返回的連接對象 if (conn == pConn.getConnection()) { // 找到了 , 設置此連接為空閑狀態 pConn.setBusy( false ); break ; } } } /** * * 刷新連接池中所有的連接對象 * * */ public synchronized void refreshConnections() throws SQLException { // 確保連接池己創新存在 if (connections == null ) { System.out.println( " 連接池不存在,無法刷新 !" ); return ; } PooledConnection pConn = null ; Enumeration enumerate = connections.elements(); while (enumerate.hasMoreElements()) { // 獲得一個連接對象 pConn = (PooledConnection) enumerate.nextElement(); // 如果對象忙則等 5 秒 ,5 秒后直接刷新 if (pConn.isBusy()) { wait( 5000 ); // 等 5 秒 } // 關閉此連接,用一個新的連接代替它。 closeConnection(pConn.getConnection()); pConn.setConnection(newConnection()); pConn.setBusy( false ); } } /** * * 關閉連接池中所有的連接,并清空連接池。 */ public synchronized void closeConnectionPool() throws SQLException { // 確保連接池存在,如果不存在,返回 if (connections == null ) { System.out.println( " 連接池不存在,無法關閉 !" ); return ; } PooledConnection pConn = null ; Enumeration enumerate = connections.elements(); while (enumerate.hasMoreElements()) { pConn = (PooledConnection) enumerate.nextElement(); // 如果忙,等 5 秒 if (pConn.isBusy()) { wait( 5000 ); // 等 5 秒 } // 5 秒后直接關閉它 closeConnection(pConn.getConnection()); // 從連接池向量中刪除它 connections.removeElement(pConn); } // 置連接池為空 connections = null ; } /** * * 關閉一個數據庫連接 * * @param 需要關閉的數據庫連接 */ private void closeConnection(Connection conn) { try { conn.close(); } catch (SQLException e) { System.out.println( " 關閉數據庫連接出錯: " + e.getMessage()); } } /** * * 使程序等待給定的毫秒數 * * @param 給定的毫秒數 */ private void wait( int mSeconds) { try { Thread.sleep(mSeconds); } catch (InterruptedException e) { } } /** * * 內部使用的用于保存連接池中連接對象的類 此類中有兩個成員,一個是數據庫的連接,另一個是指示此連接是否 正在使用的標志。 */ class PooledConnection { Connection connection = null ; // 數據庫連接 boolean busy = false ; // 此連接是否正在使用的標志,默認沒有正在使用 // 構造函數,根據一個 Connection 構告一個 PooledConnection 對象 public PooledConnection(Connection connection) { this .connection = connection; } // 返回此對象中的連接 public Connection getConnection() { return connection; } // 設置此對象的,連接 public void setConnection(Connection connection) { this .connection = connection; } // 獲得對象連接是否忙 public boolean isBusy() { return busy; } // 設置對象的連接正在忙 public void setBusy( boolean busy) { this .busy = busy; } } } |
希望本文所述對大家的java程序設計有所幫助。