1. 程式人生 > >Java數據庫連接池實現原理

Java數據庫連接池實現原理

fix 獲取 時有 .get soft div port 構造 定義

一般來說,Java應用程序訪問數據庫的過程是:
  ①裝載數據庫驅動程序;
  ②通過jdbc建立數據庫連接;
  ③訪問數據庫,執行sql語句;

  ④斷開數據庫連接。

[java] view plain copy print?
  1. public class DBConnection {
  2. private Connection con; //定義數據庫連接類對象
  3. private PreparedStatement pstm;
  4. private String user="root"; //連接數據庫用戶名
  5. private String password="123456"; //連接數據庫密碼
  6. private String driverName="com.mysql.jdbc.Driver"; //數據庫驅動
  7. private String url="jdbc:mysql://localhost:3306/qingqingtuan";
  8. //連接數據庫的URL,後面的是為了防止插入數據 庫出現亂碼,?useUnicode=true&characterEncoding=UTF-8
  9. //構造函數
  10. public DBConnection(){
  11. }
  12. /**創建數據庫連接*/
  13. public Connection getConnection(){
  14. try{
  15. Class.forName("com.mysql.jdbc.Driver");
  16. }catch(ClassNotFoundException e){
  17. System.out.println("加載數據庫驅動失敗!");
  18. e.printStackTrace();
  19. }
  20. try {
  21. con=DriverManager.getConnection(url,user,password); //獲取數據庫連接
  22. } catch (SQLException e) {
  23. System.out.println("創建數據庫連接失敗!");
  24. con=null;
  25. e.printStackTrace();
  26. }
  27. return con; //返回數據庫連接對象
  28. }
  29. List<Shop> mShopList=new ArrayList<Shop>();
  30. mConnection=new DBConnection().getConnection();
  31. if(mConnection!=null){
  32. try {
  33. String sql="select * from shop";
  34. PreparedStatement pstm=mConnection.prepareStatement(sql);
  35. ResultSet rs=pstm.executeQuery();
  36. while(rs.next()){
  37. ......//封裝PoPj的操作
  38. }
  39. rs.close();
  40. pstm.close();
  41. } catch (SQLException e) {
  42. e.printStackTrace();
  43. }finally{
  44. try {
  45. if(mConnection!=null){
  46. mConnection.close();
  47. }
  48. } catch (SQLException e) {
  49. e.printStackTrace();
  50. }
  51. }

技術分享圖片

程序開發過程中,存在很多問題:

首先,每一次web請求都要建立一次數據庫連接。建立連接是一個費時的活動,每次都得花費0.05s~1s的時間,而且系統還要分配內存資源。這個時間對於一次或幾次數據庫操作,或許感覺不出系統有多大的開銷。

可是對於現在的web應用,尤其是大型電子商務網站,同時有幾百人甚至幾千人在線是很正常的事。在這種情況下,頻繁的進行數據庫連接操作勢必占用很多的系統資源,網站的響應速度必定下降,嚴重的甚至會造成服務器的崩潰。不是危言聳聽,這就是制約某些電子商務網站發展的技術瓶頸問題。其次,對於每一次數據庫連接,使用完後都得斷開。否則,如果程序出現異常而未能關閉,將會導致數據庫系統中的內存泄漏,最終將不得不重啟數據庫

通過上面的分析,我們可以看出來,“數據庫連接”是一種稀缺的資源,為了保障網站的正常使用,應該對其進行妥善管理。實現getConnection()從連接庫中獲取一個可用的連接
③ returnConnection(conn) 提供將連接放回連接池中方法

ConnectionPool.java

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

ConnectionPoolUtils.java

[java] view plain copy print?
  1. /*連接池工具類,返回唯一的一個數據庫連接池對象,單例模式*/
  2. public class ConnectionPoolUtils {
  3. private ConnectionPoolUtils(){};//私有靜態方法
  4. private static ConnectionPool poolInstance = null;
  5. public static ConnectionPool GetPoolInstance(){
  6. if(poolInstance == null) {
  7. poolInstance = new ConnectionPool(
  8. "com.mysql.jdbc.Driver",
  9. "jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf-8",
  10. "root", "123456");
  11. try {
  12. poolInstance.createPool();
  13. } catch (Exception e) {
  14. // TODO Auto-generated catch block
  15. e.printStackTrace();
  16. }
  17. }
  18. return poolInstance;
  19. }
  20. }


ConnectionPoolTest.java

[java] view plain copy print?
  1. import java.sql.Connection;
  2. import java.sql.DriverManager;
  3. import java.sql.ResultSet;
  4. import java.sql.SQLException;
  5. import java.sql.Statement;
  6. public class ConnectionTest {
  7. /**
  8. * @param args
  9. * @throws Exception
  10. */
  11. public static void main(String[] args) throws Exception {
  12. try {
  13. /*使用連接池創建100個連接的時間*/
  14. /*// 創建數據庫連接庫對象
  15. ConnectionPool connPool = new ConnectionPool("com.mysql.jdbc.Driver","jdbc:mysql://localhost:3306/test", "root", "123456");
  16. // 新建數據庫連接庫
  17. connPool.createPool();*/
  18. ConnectionPool connPool=ConnectionPoolUtils.GetPoolInstance();//單例模式創建連接池對象
  19. // SQL測試語句
  20. String sql = "Select * from pet";
  21. // 設定程序運行起始時間
  22. long start = System.currentTimeMillis();
  23. // 循環測試100次數據庫連接
  24. for (int i = 0; i < 100; i++) {
  25. Connection conn = connPool.getConnection(); // 從連接庫中獲取一個可用的連接
  26. Statement stmt = conn.createStatement();
  27. ResultSet rs = stmt.executeQuery(sql);
  28. while (rs.next()) {
  29. String name = rs.getString("name");
  30. // System.out.println("查詢結果" + name);
  31. }
  32. rs.close();
  33. stmt.close();
  34. connPool.returnConnection(conn);// 連接使用完後釋放連接到連接池
  35. }
  36. System.out.println("經過100次的循環調用,使用連接池花費的時間:"+ (System.currentTimeMillis() - start) + "ms");
  37. // connPool.refreshConnections();//刷新數據庫連接池中所有連接,即不管連接是否正在運行,都把所有連接都釋放並放回到連接池。註意:這個耗時比較大。
  38. connPool.closeConnectionPool();// 關閉數據庫連接池。註意:這個耗時比較大。
  39. // 設定程序運行起始時間
  40. start = System.currentTimeMillis();
  41. /*不使用連接池創建100個連接的時間*/
  42. // 導入驅動
  43. Class.forName("com.mysql.jdbc.Driver");
  44. for (int i = 0; i < 100; i++) {
  45. // 創建連接
  46. Connection conn = DriverManager.getConnection(
  47. "jdbc:mysql://localhost:3306/test", "root", "123456");
  48. Statement stmt = conn.createStatement();
  49. ResultSet rs = stmt.executeQuery(sql);
  50. while (rs.next()) {
  51. }
  52. rs.close();
  53. stmt.close();
  54. conn.close();// 關閉連接
  55. }
  56. System.out.println("經過100次的循環調用,不使用連接池花費的時間:"
  57. + (System.currentTimeMillis() - start) + "ms");
  58. } catch (SQLException e) {
  59. e.printStackTrace();
  60. } catch (ClassNotFoundException e) {
  61. e.printStackTrace();
  62. }
  63. }

Java數據庫連接池實現原理