转载自   JAVA数据库连接池实现

连接池的管理用了了享元模式,这里对连接池进行简单设计。

一、设计思路

1.连接池配置属性DBbean:里面存放可以配置的一些属性

2.连接池接口IConnectionPool:里面定义一些基本的获取连接的一些方法

3.接口实现ConnectionPool:对上面操作进行实现,并加入一些其他方法

4.连接池管理ConnectionPoolManager:管理所有的不同的连接池,所有的连接都能通过这里进行获得连接

5.另外还有几个测试类,和连接信息模拟的类,这里就不进行xml 和配置文件信息的读取了

  1. package pool;
  2. /**
  3. * 这是外部可以配置的连接池属性
  4. * 可以允许外部配置,拥有默认值
  5. * @author Ran
  6. *
  7. */
  8. public class DBbean {
  9. // 连接池属性
  10. private String driverName;
  11. private String url;
  12. private String userName;
  13. private String password;
  14. // 连接池名字
  15. private String poolName;
  16. private int minConnections = 1; // 空闲池,最小连接数
  17. private int maxConnections = 10; // 空闲池,最大连接数
  18. private int initConnections = 5;// 初始化连接数
  19. private long connTimeOut = 1000;// 重复获得连接的频率
  20. private int maxActiveConnections = 100;// 最大允许的连接数,和数据库对应
  21. private long connectionTimeOut = 1000*60*20;// 连接超时时间,默认20分钟
  22. private boolean isCurrentConnection = true; // 是否获得当前连接,默认true
  23. private boolean isCheakPool = true; // 是否定时检查连接池
  24. private long lazyCheck = 1000*60*60;// 延迟多少时间后开始 检查
  25. private long periodCheck = 1000*60*60;// 检查频率
  26. public DBbean(String driverName, String url, String userName,
  27. String password, String poolName) {
  28. super();
  29. this.driverName = driverName;
  30. this.url = url;
  31. this.userName = userName;
  32. this.password = password;
  33. this.poolName = poolName;
  34. }
  35. public DBbean() {
  36. }
  37. public String getDriverName() {
  38. if(driverName == null){
  39. driverName = this.getDriverName()+"_"+this.getUrl();
  40. }
  41. return driverName;
  42. }
  43. public void setDriverName(String driverName) {
  44. this.driverName = driverName;
  45. }
  46. public String getUrl() {
  47. return url;
  48. }
  49. public void setUrl(String url) {
  50. this.url = url;
  51. }
  52. public String getUserName() {
  53. return userName;
  54. }
  55. public void setUserName(String userName) {
  56. this.userName = userName;
  57. }
  58. public String getPassword() {
  59. return password;
  60. }
  61. public void setPassword(String password) {
  62. this.password = password;
  63. }
  64. public String getPoolName() {
  65. return poolName;
  66. }
  67. public void setPoolName(String poolName) {
  68. this.poolName = poolName;
  69. }
  70. public int getMinConnections() {
  71. return minConnections;
  72. }
  73. public void setMinConnections(int minConnections) {
  74. this.minConnections = minConnections;
  75. }
  76. public int getMaxConnections() {
  77. return maxConnections;
  78. }
  79. public void setMaxConnections(int maxConnections) {
  80. this.maxConnections = maxConnections;
  81. }
  82. public int getInitConnections() {
  83. return initConnections;
  84. }
  85. public void setInitConnections(int initConnections) {
  86. this.initConnections = initConnections;
  87. }
  88. public int getMaxActiveConnections() {
  89. return maxActiveConnections;
  90. }
  91. public void setMaxActiveConnections(int maxActiveConnections) {
  92. this.maxActiveConnections = maxActiveConnections;
  93. }
  94. public long getConnTimeOut() {
  95. return connTimeOut;
  96. }
  97. public void setConnTimeOut(long connTimeOut) {
  98. this.connTimeOut = connTimeOut;
  99. }
  100. public long getConnectionTimeOut() {
  101. return connectionTimeOut;
  102. }
  103. public void setConnectionTimeOut(long connectionTimeOut) {
  104. this.connectionTimeOut = connectionTimeOut;
  105. }
  106. public boolean isCurrentConnection() {
  107. return isCurrentConnection;
  108. }
  109. public void setCurrentConnection(boolean isCurrentConnection) {
  110. this.isCurrentConnection = isCurrentConnection;
  111. }
  112. public long getLazyCheck() {
  113. return lazyCheck;
  114. }
  115. public void setLazyCheck(long lazyCheck) {
  116. this.lazyCheck = lazyCheck;
  117. }
  118. public long getPeriodCheck() {
  119. return periodCheck;
  120. }
  121. public void setPeriodCheck(long periodCheck) {
  122. this.periodCheck = periodCheck;
  123. }
  124. public boolean isCheakPool() {
  125. return isCheakPool;
  126. }
  127. public void setCheakPool(boolean isCheakPool) {
  128. this.isCheakPool = isCheakPool;
  129. }
  130. }
Java代码  
  1. package pool;
  2. import java.sql.Connection;
  3. import java.sql.SQLException;
  4. public interface IConnectionPool {
  5. // 获得连接
  6. public Connection  getConnection();
  7. // 获得当前连接
  8. public Connection getCurrentConnecton();
  9. // 回收连接
  10. public void releaseConn(Connection conn) throws SQLException;
  11. // 销毁清空
  12. public void destroy();
  13. // 连接池是活动状态
  14. public boolean isActive();
  15. // 定时器,检查连接池
  16. public void cheackPool();
  17. }
  1. package pool;
  2. import java.sql.Connection;
  3. import java.sql.DriverManager;
  4. import java.sql.SQLException;
  5. import java.util.List;
  6. import java.util.Timer;
  7. import java.util.TimerTask;
  8. import java.util.Vector;
  9. public class ConnectionPool implements IConnectionPool {
  10. // 连接池配置属性
  11. private DBbean dbBean;
  12. private boolean isActive = false; // 连接池活动状态
  13. private int contActive = 0;// 记录创建的总的连接数
  14. // 空闲连接
  15. private List<Connection> freeConnection = new Vector<Connection>();
  16. // 活动连接
  17. private List<Connection> activeConnection = new Vector<Connection>();
  18. // 将线程和连接绑定,保证事务能统一执行
  19. private static ThreadLocal<Connection> threadLocal = new ThreadLocal<Connection>();
  20. public ConnectionPool(DBbean dbBean) {
  21. super();
  22. this.dbBean = dbBean;
  23. init();
  24. cheackPool();
  25. }
  26. // 初始化
  27. public void init() {
  28. try {
  29. Class.forName(dbBean.getDriverName());
  30. for (int i = 0; i < dbBean.getInitConnections(); i++) {
  31. Connection conn;
  32. conn = newConnection();
  33. // 初始化最小连接数
  34. if (conn != null) {
  35. freeConnection.add(conn);
  36. contActive++;
  37. }
  38. }
  39. isActive = true;
  40. } catch (ClassNotFoundException e) {
  41. e.printStackTrace();
  42. } catch (SQLException e) {
  43. e.printStackTrace();
  44. }
  45. }
  46. // 获得当前连接
  47. public Connection getCurrentConnecton(){
  48. // 默认线程里面取
  49. Connection conn = threadLocal.get();
  50. if(!isValid(conn)){
  51. conn = getConnection();
  52. }
  53. return conn;
  54. }
  55. // 获得连接
  56. public synchronized Connection getConnection() {
  57. Connection conn = null;
  58. try {
  59. // 判断是否超过最大连接数限制
  60. if(contActive < this.dbBean.getMaxActiveConnections()){
  61. if (freeConnection.size() > 0) {
  62. conn = freeConnection.get(0);
  63. if (conn != null) {
  64. threadLocal.set(conn);
  65. }
  66. freeConnection.remove(0);
  67. } else {
  68. conn = newConnection();
  69. }
  70. }else{
  71. // 继续获得连接,直到从新获得连接
  72. wait(this.dbBean.getConnTimeOut());
  73. conn = getConnection();
  74. }
  75. if (isValid(conn)) {
  76. activeConnection.add(conn);
  77. contActive ++;
  78. }
  79. } catch (SQLException e) {
  80. e.printStackTrace();
  81. } catch (ClassNotFoundException e) {
  82. e.printStackTrace();
  83. } catch (InterruptedException e) {
  84. e.printStackTrace();
  85. }
  86. return conn;
  87. }
  88. // 获得新连接
  89. private synchronized Connection newConnection()
  90. throws ClassNotFoundException, SQLException {
  91. Connection conn = null;
  92. if (dbBean != null) {
  93. Class.forName(dbBean.getDriverName());
  94. conn = DriverManager.getConnection(dbBean.getUrl(),
  95. dbBean.getUserName(), dbBean.getPassword());
  96. }
  97. return conn;
  98. }
  99. // 释放连接
  100. public synchronized void releaseConn(Connection conn) throws SQLException {
  101. if (isValid(conn)&& !(freeConnection.size() > dbBean.getMaxConnections())) {
  102. freeConnection.add(conn);
  103. activeConnection.remove(conn);
  104. contActive --;
  105. threadLocal.remove();
  106. // 唤醒所有正待等待的线程,去抢连接
  107. notifyAll();
  108. }
  109. }
  110. // 判断连接是否可用
  111. private boolean isValid(Connection conn) {
  112. try {
  113. if (conn == null || conn.isClosed()) {
  114. return false;
  115. }
  116. } catch (SQLException e) {
  117. e.printStackTrace();
  118. }
  119. return true;
  120. }
  121. // 销毁连接池
  122. public synchronized void destroy() {
  123. for (Connection conn : freeConnection) {
  124. try {
  125. if (isValid(conn)) {
  126. conn.close();
  127. }
  128. } catch (SQLException e) {
  129. e.printStackTrace();
  130. }
  131. }
  132. for (Connection conn : activeConnection) {
  133. try {
  134. if (isValid(conn)) {
  135. conn.close();
  136. }
  137. } catch (SQLException e) {
  138. e.printStackTrace();
  139. }
  140. }
  141. isActive = false;
  142. contActive = 0;
  143. }
  144. // 连接池状态
  145. @Override
  146. public boolean isActive() {
  147. return isActive;
  148. }
  149. // 定时检查连接池情况
  150. @Override
  151. public void cheackPool() {
  152. if(dbBean.isCheakPool()){
  153. new Timer().schedule(new TimerTask() {
  154. @Override
  155. public void run() {
  156. // 1.对线程里面的连接状态
  157. // 2.连接池最小 最大连接数
  158. // 3.其他状态进行检查,因为这里还需要写几个线程管理的类,暂时就不添加了
  159. System.out.println("空线池连接数:"+freeConnection.size());
  160. System.out.println("活动连接数::"+activeConnection.size());
  161. System.out.println("总的连接数:"+contActive);
  162. }
  163. },dbBean.getLazyCheck(),dbBean.getPeriodCheck());
  164. }
  165. }
  166. }
  1. package pool;
  2. import java.sql.Connection;
  3. import java.sql.SQLException;
  4. import java.util.Hashtable;
  5. /**
  6. * 连接管理类
  7. * @author Ran
  8. *
  9. */
  10. public class ConnectionPoolManager {
  11. // 连接池存放
  12. public Hashtable<String,IConnectionPool> pools = new Hashtable<String, IConnectionPool>();
  13. // 初始化
  14. private ConnectionPoolManager(){
  15. init();
  16. }
  17. // 单例实现
  18. public static ConnectionPoolManager getInstance(){
  19. return Singtonle.instance;
  20. }
  21. private static class Singtonle {
  22. private static ConnectionPoolManager instance =  new ConnectionPoolManager();
  23. }
  24. // 初始化所有的连接池
  25. public void init(){
  26. for(int i =0;i<DBInitInfo.beans.size();i++){
  27. DBbean bean = DBInitInfo.beans.get(i);
  28. ConnectionPool pool = new ConnectionPool(bean);
  29. if(pool != null){
  30. pools.put(bean.getPoolName(), pool);
  31. System.out.println("Info:Init connection successed ->" +bean.getPoolName());
  32. }
  33. }
  34. }
  35. // 获得连接,根据连接池名字 获得连接
  36. public Connection  getConnection(String poolName){
  37. Connection conn = null;
  38. if(pools.size()>0 && pools.containsKey(poolName)){
  39. conn = getPool(poolName).getConnection();
  40. }else{
  41. System.out.println("Error:Can't find this connecion pool ->"+poolName);
  42. }
  43. return conn;
  44. }
  45. // 关闭,回收连接
  46. public void close(String poolName,Connection conn){
  47. IConnectionPool pool = getPool(poolName);
  48. try {
  49. if(pool != null){
  50. pool.releaseConn(conn);
  51. }
  52. } catch (SQLException e) {
  53. System.out.println("连接池已经销毁");
  54. e.printStackTrace();
  55. }
  56. }
  57. // 清空连接池
  58. public void destroy(String poolName){
  59. IConnectionPool pool = getPool(poolName);
  60. if(pool != null){
  61. pool.destroy();
  62. }
  63. }
  64. // 获得连接池
  65. public IConnectionPool getPool(String poolName){
  66. IConnectionPool pool = null;
  67. if(pools.size() > 0){
  68. pool = pools.get(poolName);
  69. }
  70. return pool;
  71. }
  72. }
  1. package pool;
  2. import java.util.ArrayList;
  3. import java.util.List;
  4. /**
  5. * 初始化,模拟加载所有的配置文件
  6. * @author Ran
  7. *
  8. */
  9. public class DBInitInfo {
  10. public  static List<DBbean>  beans = null;
  11. static{
  12. beans = new ArrayList<DBbean>();
  13. // 这里数据 可以从xml 等配置文件进行获取
  14. // 为了测试,这里我直接写死
  15. DBbean beanOracle = new DBbean();
  16. beanOracle.setDriverName("oracle.jdbc.driver.OracleDriver");
  17. beanOracle.setUrl("jdbc:oracle:thin:@7MEXGLUY95W1Y56:1521:orcl");
  18. beanOracle.setUserName("mmsoa");
  19. beanOracle.setPassword("password1234");
  20. beanOracle.setMinConnections(5);
  21. beanOracle.setMaxConnections(100);
  22. beanOracle.setPoolName("testPool");
  23. beans.add(beanOracle);
  24. }
  25. }

测试:

  1. package pool;
  2. import java.sql.Connection;
  3. /**
  4. * 模拟线程启动,去获得连接
  5. * @author Ran
  6. *
  7. */
  8. public class ThreadConnection implements Runnable{
  9. private IConnectionPool pool;
  10. @Override
  11. public void run() {
  12. pool = ConnectionPoolManager.getInstance().getPool("testPool");
  13. }
  14. public Connection getConnection(){
  15. Connection conn = null;
  16. if(pool != null && pool.isActive()){
  17. conn = pool.getConnection();
  18. }
  19. return conn;
  20. }
  21. public Connection getCurrentConnection(){
  22. Connection conn = null;
  23. if(pool != null && pool.isActive()){
  24. conn = pool.getCurrentConnecton();
  25. }
  26. return conn;
  27. }
  28. }
  1. package pool;
  2. public class Client {
  3. public static void main(String[] args) throws InterruptedException {
  4. // 初始化连接池
  5. Thread t = init();
  6. t.start();
  7. t.join();
  8. ThreadConnection a = new ThreadConnection();
  9. ThreadConnection b = new ThreadConnection();
  10. ThreadConnection c = new ThreadConnection();
  11. Thread t1 = new Thread(a);
  12. Thread t2 = new Thread(b);
  13. Thread t3 = new Thread(c);
  14. // 设置优先级,先让初始化执行,模拟 线程池 先启动
  15. // 这里仅仅表面控制了,因为即使t 线程先启动,也不能保证pool 初始化完成,为了简单模拟,这里先这样写了
  16. t1.setPriority(10);
  17. t2.setPriority(10);
  18. t3.setPriority(10);
  19. t1.start();
  20. t2.start();
  21. t3.start();
  22. System.out.println("线程A-> "+a.getConnection());
  23. System.out.println("线程B-> "+b.getConnection());
  24. System.out.println("线程C-> "+c.getConnection());
  25. }
  26. // 初始化
  27. public static Thread init() {
  28. Thread t = new Thread(new Runnable() {
  29. @Override
  30. public void run() {
  31. IConnectionPool  pool = initPool();
  32. while(pool == null || !pool.isActive()){
  33. pool = initPool();
  34. }
  35. }
  36. });
  37. return t;
  38. }
  39. public static IConnectionPool initPool(){
  40. return ConnectionPoolManager.getInstance().getPool("testPool");
  41. }
  42. }

小结 :

1.连接池诞生原因是,如果每次都从数据库获得连接,时间比较长,因此我们提前做建立一些连接,放在连接池里面,每次都从里面取

2.上面仅仅写了连接池基本原理,关于多线程下连接池的管理没写,后面对多线程操作熟练了添加吧

JAVA数据库连接池实现相关推荐

  1. 主流Java数据库连接池比较及前瞻

    本文转载自微信公众号「工匠小猪猪的技术世界」 主流数据库连接池 常用的主流开源数据库连接池有C3P0.DBCP.Tomcat Jdbc Pool.BoneCP.Druid等 C3p0: 开源的JDBC ...

  2. Java数据库连接池实现原理

    https://blog.csdn.net/tuke_tuke/article/details/51532510 一般来说,Java应用程序访问数据库的过程是: ①装载数据库驱动程序: ②通过jdbc ...

  3. 主流Java数据库连接池分析(C3P0,DBCP,TomcatPool,BoneCP,Druid)

    http://developer.51cto.com/art/201807/579402.htm 主流数据库连接池 常用的主流开源数据库连接池有C3P0.DBCP.Tomcat Jdbc Pool.B ...

  4. Java数据库连接池--DBCP浅析

    转载自   Java数据库连接池--DBCP浅析 前言对于数据库连接池, 想必大家都已经不再陌生, 这里仅仅设计Java中的两个常用数据库连接池: DBCP和C3P0(后续会更新). 一. 为何要使用 ...

  5. Java 数据库连接池的技术选型都应考虑哪些要素

    为什么80%的码农都做不了架构师?>>>    数据库连接池是一个牵涉面很广的话题,对于大型系统,数据库连接池的好坏,关系到系统的性能和稳定性,因此,选好数据库连接池,是系统在架构时 ...

  6. mysql连接池源码_一个JAVA数据库连接池实现源码

    原文链接:http://www.open-open.com/lib/view/open1410875608164.html // // 一个效果非常不错的JAVA数据库连接池. // from:htt ...

  7. java数据库连接池选择及开发配置

    一.数据库连接池概述 数据库连接的建立是一种耗时.性能低.代价高的操作,频繁的数据库连接的建立和关闭极大的影响了系统的性能.数据库连接池是系统初始化过程中创建一定数量的数据库连接放于连接池中,当程序需 ...

  8. java 连接池 druid_从零开始学 Java - 数据库连接池的选择 Druid

    我先说说数据库连接 数据库大家都不陌生,从名字就能看出来它是「存放数据的仓库」,那我们怎么去「仓库」取东西呢?当然需要钥匙啦!这就是我们的数据库用户名.密码了,然后我们就可以打开门去任意的存取东西了. ...

  9. java 数据库连接池 实例_java数据库连接池和数据库连接示例

    import java.sql.Connection; import java.sql.SQLException; import javax.sql.DataSource; import com.mc ...

最新文章

  1. 2021年大数据Hadoop(十):HDFS的数据读写流程
  2. ASP.NET MVC Module
  3. isinfinite_Java Double类isInfinite()方法与示例
  4. 35. 复杂链表的复制
  5. android安装apk提示版本号不同,android 安装apk 遇到的问题
  6. android 速度传感器,Android实战技巧之四十二:加速度传感器
  7. 定时重启_SpringBoot基于数据库的定时任务实现方法
  8. 项目管理软件之禅道和JIRA的共同点与区别
  9. 微信小程序申请微信支付0.2费率商户号微信小程序接入开通流程
  10. Pyrene-PEG-Acid,芘丁酸聚乙二醇羧基,Pyrene-PEG-COOH
  11. 被指开除高级研究员,谷歌大神Jeff Dean回应:是她说不答应条件就离职
  12. OpenGL课程设计 三维图形交互程序 bunny兔+飞机模型
  13. 周记——20150907
  14. 扔掉代码,程序员月薪达到了10k+
  15. 沈剑架构师之路的分享-总结
  16. blog群发王(价值1980元)源代码提供 1
  17. php打印10以内减法表,10以内加减法口诀表(A4纸可以打印)
  18. 手机上的磁性传感技术
  19. web前端开发之vue基础
  20. Android_AsyncTaskDemo之QQ记步数(画圆形图片知识)

热门文章

  1. 二叉树最近公共祖先相关题目(Leetcode题解-Python语言)
  2. 使用React hooks,些许又多了不少摸鱼时间
  3. 《C++ Primer》2.6.1节练习
  4. 中科大软件测试期末复习
  5. php mysql 子查询_php – MySQL查询和子查询
  6. cubemx lan8720模块_通过STM32cubeMX将STM32F767+LAN8720+LwIP+FreeRTOS的以太网实现
  7. PTA 三足鼎立 (lower_bound()+upper_bound())
  8. Spring boot——起步依赖
  9. 51 NOD 1363 最小公倍数之和 (欧拉函数思维应用)
  10. Harbour.Space Scholarship Contest 2021-2022 F. Pairwise Modulo 逆向思维 + 树状数组