ITeye博客

(转)java 数据库连接池的实现代码

星海孤舟 · 2010-12-22 12:30 · 企业架构 · Java · SQL · JDBC · thread · Markdown

java 数据库连接池的实现代码

复制代码

  1. package com.xiaobian;
  2. /**
  3. * 数据库连接池管理类
  4. */
  5. import java.io.*;
  6. import java.sql.*;
  7. import java.util.*;
  8. import java.util.Date;
  9. /**
  10. * 管理类DBConnectionManager支持对一个或多个由属性文件定义的数据库连接池的
  11. * 访问.客户程序可以调用getInstance()方法访问本类的唯一实例
  12. */
  13. public class DBConnectionManager {
  14. public static void main(String[] args) {
  15. DBConnectionManager connectionManager = DBConnectionManager.getInstance();
  16. Connection conn =  connectionManager.getConnection("idb");
  17. try {
  18. Thread.sleep(10);
  19. } catch (InterruptedException e) {
  20. // TODO Auto-generated catch block
  21. e.printStackTrace();
  22. }
  23. Connection conn1 =  connectionManager.getConnection("idb");
  24. Connection conn2 =  connectionManager.getConnection("idb");
  25. Connection conn3 =  connectionManager.getConnection("idb");
  26. Connection conn4 =  connectionManager.getConnection("idb");
  27. Connection conn5 =  connectionManager.getConnection("idb");
  28. connectionManager.freeConnection("idb", conn);
  29. connectionManager.freeConnection("idb", conn1);
  30. connectionManager.freeConnection("idb", conn2);
  31. connectionManager.freeConnection("idb", conn3);
  32. connectionManager.freeConnection("idb", conn4);
  33. connectionManager.freeConnection("idb", conn5);
  34. Connection conn6 = connectionManager.getConnection("idb");
  35. Connection conn7 = connectionManager.getConnection("idb");
  36. System.out.println(" conn6 == "+conn6 +" conn7 == "+conn7);
  37. }
  38. static private DBConnectionManager instance; // 唯一实例
  39. static private int clients; //
  40. private Vector drivers = new Vector();
  41. private PrintWriter log;
  42. private Hashtable pools = new Hashtable();
  43. /**
  44. * 返回唯一实例.如果是第一次调用此方法,则创建实例
  45. *
  46. * @return DBConnectionManager 唯一实例
  47. */
  48. static synchronized public DBConnectionManager getInstance() {
  49. if (instance == null) {
  50. instance = new DBConnectionManager();
  51. }
  52. clients++;
  53. return instance;
  54. }
  55. /**
  56. * 建构私有函数以防止其它对象创建本类实例
  57. */
  58. private DBConnectionManager() {
  59. init();
  60. }
  61. /**
  62. * 将连接对象返回给由名字指定的连接池
  63. *
  64. * @param name
  65. *            在属性文件中定义的连接池名字
  66. * @param con
  67. *            连接对象
  68. */
  69. public void freeConnection(String name, Connection con) {
  70. DBConnectionPool pool = (DBConnectionPool) pools.get(name);
  71. if (pool != null) {
  72. pool.freeConnection(con);
  73. }
  74. }
  75. /**
  76. * 获得一个可用的(空闲的)连接.如果没有可用连接,且已有连接数小于最大连接数 限制,则创建并返回新连接
  77. *
  78. * @param name
  79. *            在属性文件中定义的连接池名字
  80. * @return Connection 可用连接或null
  81. */
  82. public Connection getConnection(String name) {
  83. DBConnectionPool pool = (DBConnectionPool) pools.get(name);
  84. //System.out.println(" pool == "+pool);
  85. if (pool != null) {
  86. return pool.getConnection();
  87. }
  88. return null;
  89. }
  90. /**
  91. * 获得一个可用连接.若没有可用连接,且已有连接数小于最大连接数限制, 则创建并返回新连接.否则,在指定的时间内等待其它线程释放连接.
  92. *
  93. * @param name
  94. *            连接池名字
  95. * @param time
  96. *            以毫秒计的等待时间
  97. * @return Connection 可用连接或null
  98. */
  99. public Connection getConnection(String name, long time) {
  100. DBConnectionPool pool = (DBConnectionPool) pools.get(name);
  101. if (pool != null) {
  102. return pool.getConnection(time);
  103. }
  104. return null;
  105. }
  106. /**
  107. * 关闭所有连接,撤销驱动程序的注册
  108. */
  109. public synchronized void release() {
  110. // 等待直到最后一个客户程序调用
  111. if (--clients != 0) {
  112. return;
  113. }
  114. Enumeration allPools = pools.elements();
  115. while (allPools.hasMoreElements()) {
  116. DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
  117. pool.release();
  118. }
  119. Enumeration allDrivers = drivers.elements();
  120. while (allDrivers.hasMoreElements()) {
  121. Driver driver = (Driver) allDrivers.nextElement();
  122. try {
  123. DriverManager.deregisterDriver(driver);
  124. log("撤销JDBC驱动程序 " + driver.getClass().getName() + "的注册");
  125. } catch (SQLException e) {
  126. log(e, "无法撤销下列JDBC驱动程序的注册: " + driver.getClass().getName());
  127. }
  128. }
  129. }
  130. /**
  131. * 根据指定属性创建连接池实例.
  132. *
  133. * @param props
  134. *            连接池属性
  135. */
  136. private void createPools(Properties props) {
  137. Enumeration propNames = props.propertyNames();
  138. while (propNames.hasMoreElements()) {
  139. String name = (String) propNames.nextElement();
  140. if (name.endsWith(".url")) {
  141. String poolName = name.substring(0, name.lastIndexOf("."));
  142. //System.out.println(" poolName ||"+poolName+"|");
  143. String url = props.getProperty(poolName + ".url");
  144. if (url == null) {
  145. log("没有为连接池" + poolName + "指定URL");
  146. continue;
  147. }
  148. String user = props.getProperty(poolName + ".user");
  149. String password = props.getProperty(poolName + ".password");
  150. String maxconn = props.getProperty(poolName + ".maxconn", "0");
  151. int max;
  152. try {
  153. max = Integer.valueOf(maxconn).intValue();
  154. } catch (NumberFormatException e) {
  155. log("错误的最大连接数限制: " + maxconn + " .连接池: " + poolName);
  156. max = 0;
  157. }
  158. DBConnectionPool pool = new DBConnectionPool(poolName, url,
  159. user, password, max);
  160. pools.put(poolName, pool);
  161. log("成功创建连接池" + poolName);
  162. }
  163. }
  164. }
  165. // --------------------------------------------------------------------------------
  166. /**
  167. * 读取属性完成初始化
  168. */
  169. private void init() {
  170. InputStream fileinputstream = null;
  171. try {
  172. fileinputstream = new FileInputStream("./src/db.properties");
  173. } catch (FileNotFoundException e1) {
  174. e1.printStackTrace();
  175. }
  176. //BufferedReader bufferedreader = new BufferedReader(new InputStreamReader(fileinputstream));
  177. //InputStream is = getClass().getResourceAsStream("D:/workspace/UmessageSms/src/db.properties");
  178. Properties dbProps = new Properties();
  179. try {
  180. dbProps.load(fileinputstream);
  181. } catch (Exception e) {
  182. e.printStackTrace();
  183. System.err.println("不能读取属性文件. "
  184. + "请确保db.properties在CLASSPATH指定的路径中");
  185. return;
  186. }
  187. String logFile = dbProps.getProperty("logfile",
  188. "DBConnectionManager.log");
  189. //System.out.println(dbProps.getProperty("logfile"));
  190. try {
  191. log = new PrintWriter(new FileWriter(logFile, true), true);
  192. } catch (IOException e) {
  193. System.err.println("无法打开日志文件: " + logFile);
  194. log = new PrintWriter(System.err);
  195. }
  196. loadDrivers(dbProps);
  197. createPools(dbProps);
  198. }
  199. /**
  200. * 装载和注册所有JDBC驱动程序
  201. *
  202. * @param props
  203. *            属性
  204. */
  205. private void loadDrivers(Properties props) {
  206. String driverClasses = props.getProperty("drivers");
  207. StringTokenizer st = new StringTokenizer(driverClasses);
  208. while (st.hasMoreElements()) {
  209. String driverClassName = st.nextToken().trim();
  210. try {
  211. Driver driver = (Driver) Class.forName(driverClassName)
  212. .newInstance();
  213. DriverManager.registerDriver(driver);
  214. drivers.addElement(driver);
  215. log("成功注册JDBC驱动程序" + driverClassName);
  216. } catch (Exception e) {
  217. log("无法注册JDBC驱动程序: " + driverClassName + ", 错误: " + e);
  218. }
  219. }
  220. }
  221. /**
  222. * 将文本信息写入日志文件
  223. */
  224. private void log(String msg) {
  225. log.println(new Date() + ": " + msg);
  226. }
  227. /**
  228. * 将文本信息与异常写入日志文件
  229. */
  230. private void log(Throwable e, String msg) {
  231. log.println(new Date() + ": " + msg);
  232. e.printStackTrace(log);
  233. }
  234. /** ************************************************************* */
  235. /** ********************内部类DBConnectionPool******************** */
  236. /** ************************************************************* */
  237. /**
  238. * 此内部类定义了一个连接池.它能够根据要求创建新连接,直到预定的最 大连接数为止.在返回连接给客户程序之前,它能够验证连接的有效性.
  239. */
  240. class DBConnectionPool {
  241. private int checkedOut; // 当前连接数
  242. private Vector freeConnections = new Vector(); // 保存所有可用连接
  243. private int maxConn; // 此连接池允许建立的最大连接数
  244. private String name; // 连接池名字
  245. private String password; // 密码或null
  246. private String URL; // 数据库的JDBC URL
  247. private String user; // 数据库账号或null
  248. /**
  249. * 创建新的连接池
  250. *
  251. * @param name
  252. *            连接池名字
  253. * @param URL
  254. *            数据库的JDBC URL
  255. * @param user
  256. *            数据库帐号或 null
  257. * @param password
  258. *            密码或 null
  259. * @param maxConn
  260. *            此连接池允许建立的最大连接数
  261. */
  262. public DBConnectionPool(String name, String URL, String user,
  263. String password, int maxConn) {
  264. this.name = name;
  265. this.URL = URL;
  266. this.user = user;
  267. this.password = password;
  268. this.maxConn = maxConn;
  269. }
  270. /**
  271. * 将不再使用的连接返回给连接池
  272. *
  273. * @param con
  274. *            客户程序释放的连接
  275. */
  276. public synchronized void freeConnection(Connection con) {
  277. // 将指定连接加入到向量末尾
  278. freeConnections.addElement(con);
  279. checkedOut--;
  280. notifyAll(); // 删除等待队列中的所有线程
  281. }
  282. /**
  283. * 从连接池获得一个可用连接.如果没有空闲的连接且当前连接数小于最大连接
  284. * 数限制,则创建新连接.如原来登记为可用的连接不再有效,则从向量删除之, 然后递归调用自己以尝试新的可用连接.
  285. */
  286. public synchronized Connection getConnection() {
  287. Connection con = null;
  288. //System.out.println(" freeConnections.size() "+freeConnections.size());
  289. if (freeConnections.size() > 0) {
  290. // 获取向量中第一个可用连接
  291. con = (Connection) freeConnections.firstElement();
  292. freeConnections.removeElementAt(0);
  293. try {
  294. if (con.isClosed()) {
  295. log("从连接池" + name + "删除一个无效连接");
  296. // 递归调用自己,尝试再次获取可用连接
  297. con = getConnection();
  298. }
  299. } catch (SQLException e) {
  300. log("从连接池" + name + "删除一个无效连接");
  301. // 递归调用自己,尝试再次获取可用连接
  302. con = getConnection();
  303. }
  304. } else if (maxConn == 0 || checkedOut < maxConn) {
  305. con = newConnection();
  306. }
  307. if (con != null) {
  308. checkedOut++;
  309. }
  310. System.out.println("con == "+con);
  311. return con;
  312. }
  313. /**
  314. * 从连接池获取可用连接.可以指定客户程序能够等待的最长时间 参见前一个getConnection()方法.
  315. *
  316. * @param timeout
  317. *            以毫秒计的等待时间限制
  318. */
  319. public synchronized Connection getConnection(long timeout) {
  320. long startTime = new Date().getTime();
  321. Connection con;
  322. while ((con = getConnection()) == null) {
  323. try {
  324. wait(timeout);
  325. } catch (InterruptedException e) {
  326. }
  327. if ((new Date().getTime() - startTime) >= timeout) {
  328. // wait()返回的原因是超时
  329. return null;
  330. }
  331. }
  332. return con;
  333. }
  334. /**
  335. * 关闭所有连接
  336. */
  337. public synchronized void release() {
  338. Enumeration allConnections = freeConnections.elements();
  339. while (allConnections.hasMoreElements()) {
  340. Connection con = (Connection) allConnections.nextElement();
  341. try {
  342. con.close();
  343. log("关闭连接池" + name + "中的一个连接");
  344. } catch (SQLException e) {
  345. log(e, "无法关闭连接池" + name + "中的连接");
  346. }
  347. }
  348. freeConnections.removeAllElements();
  349. }
  350. /**
  351. * 创建新的连接
  352. */
  353. private Connection newConnection() {
  354. Connection con = null;
  355. try {
  356. if (user == null) {
  357. con = DriverManager.getConnection(URL);
  358. } else {
  359. con = DriverManager.getConnection(URL, user, password);
  360. }
  361. log("连接池" + name + "创建一个新的连接");
  362. } catch (SQLException e) {
  363. log(e, "无法创建下列URL的连接: " + URL);
  364. return null;
  365. }
  366. return con;
  367. }
  368. }
  369. }

评论(0)

暂无评论。

评论功能维护中,当前仅展示历史评论。