java实现数据库连接池

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

ConnectionParam.java

    1. package com.kyo.connection;
    2. import java.io.Serializable;
    3. /**
    4. * @author niudongjie.pt 数据库连接池参数
    5. */
    6. public class ConnectionParam implements Serializable {
    7. /**
    8. *
    9. */
    10. private static final long serialVersionUID = 1L;
    11. private String driver; // 数据库连接驱动
    12. private String url; // 数据库连接URL
    13. private String user; // 数据库连接user
    14. private String password; // 数据库连接password
    15. private int minConnection; // 数据库连接池最小连接数
    16. private int maxConnection; // 数据库连接池最大连接数
    17. private long timeoutValue; // 连接的最大空闲时间
    18. private long waitTime; // 取得连接的最大等待时间
    19. private int incrementalConnections=5; //连接池自动增加连接的数量
    20. public String getDriver() {
    21. return driver;
    22. }
    23. public void setDriver(String driver) {
    24. this.driver = driver;
    25. }
    26. public String getUrl() {
    27. return url;
    28. }
    29. public void setUrl(String url) {
    30. this.url = url;
    31. }
    32. public String getUser() {
    33. return user;
    34. }
    35. public void setUser(String user) {
    36. this.user = user;
    37. }
    38. public String getPassword() {
    39. return password;
    40. }
    41. public void setPassword(String password) {
    42. this.password = password;
    43. }
    44. public int getMinConnection() {
    45. return minConnection;
    46. }
    47. public void setMinConnection(int minConnection) {
    48. this.minConnection = minConnection;
    49. }
    50. public int getMaxConnection() {
    51. return maxConnection;
    52. }
    53. public void setMaxConnection(int maxConnection) {
    54. this.maxConnection = maxConnection;
    55. }
    56. public long getTimeoutValue() {
    57. return timeoutValue;
    58. }
    59. public void setTimeoutValue(long timeoutValue) {
    60. this.timeoutValue = timeoutValue;
    61. }
    62. public long getWaitTime() {
    63. return waitTime;
    64. }
    65. public void setWaitTime(long waitTime) {
    66. this.waitTime = waitTime;
    67. }
    68. public void setIncrementalConnections(int incrementalConnections) {
    69. this.incrementalConnections = incrementalConnections;
    70. }
    71. public int getIncrementalConnections() {
    72. return incrementalConnections;
    73. }
    74. }