• 连接池-归还连接详解(上)


    • 目录

      归还数据库连接的方式

      继承方式归还数据库连接的思想

      继承方式归还数据库连接的实现步骤

      继承方式归还数据库连接存在的问题

      装饰设计模式归还数据库连接的思想

      装饰设计模式归还数据库连接的实现步骤

      装饰设计模式归还数据库连接存在的问题

      装饰设计模式归还实例演示


    • 归还数据库连接的方式

    • 继承方式
    • 装饰设计模式
    • 适配器设计模式
    • 动态代理方式
    • 继承方式归还数据库连接的思想

    • 通过打印连接对象,发现DriverManager获取的连接实现类是JDBC4Connection
    • 那我们就可以自定义一个类,继承JDBC4Connection这个类,重写close()方法,完成连接对象的归还
    • 继承方式归还数据库连接的实现步骤

    • 1.定义一个类,继承JDBC4Connection
    • 2.定义Connection连接对象和连接池容器对象的成员变量
    • 3.通过有参构造方法完成对成员变量的赋值
    • 4.重写close方法,将连接对象添加到池中
    • 继承方式归还数据库连接存在的问题

    • 通过查看JDBC工具类获取连接的方法发现
    • 我们虽然自定义了一个子类,完成了归还连接操作
    • 但是DriverManager获取的还是JDBC4Connection这个对象,并不是我们的子类对象
    • 而我们又不能整体去修改驱动包中类的功能,所以继承这种方式行不通
    • 装饰设计模式归还数据库连接的思想

    • 我们可以自定义一个类,实现Connection接口
    • 这样就具备了和JDBC4Connection相同的行为了
    • 重写close()方法,完成连接的归还
    • 其余的功能还调用mysql驱动包实现类原有的方法即可
    • 装饰设计模式归还数据库连接的实现步骤

    • 1.定义一个类,实现Connection接口
    • 2.定义Connection连接对象和连接池容器对象的成员变量
    • 3.通过有参构造方法完成对成员变量的赋值
    • 4.重写close()方法,将连接对象添加到池中
    • 5.剩余方法,只需要调用mysql驱动包的连接对象完成即可
    • 6.在自定义连接池中,将获取的连接对象通过自定义连接对象进行包装
    • 装饰设计模式归还数据库连接存在的问题

    • 实现Connection接口后
    • 有大量的方法需要在自定义类中重写
    • 装饰设计模式归还实例演示

      1. package demo02.myDataSourse;
      2. import java.sql.*;
      3. import java.util.List;
      4. import java.util.Map;
      5. import java.util.Properties;
      6. import java.util.concurrent.Executor;
      7. //1.定义一个类,实现Connection接口
      8. public class demomyConnection implements Connection {
      9. //2.定义连接对象和连接池容器对象的成员变量
      10. private Connection con;
      11. private List pool;
      12. //3.通过有参构造方法为成员变量赋值
      13. public demomyConnection(Connection con, List pool) {
      14. this.con = con;
      15. this.pool = pool;
      16. }
      17. //4.重写close方法,完成归还连接
      18. @Override
      19. public void close() throws SQLException {
      20. pool.add(con);
      21. }
      22. //5.剩余方法,还是调用原有的连接对象中的功能即可
      23. @Override
      24. public Statement createStatement() throws SQLException {
      25. return con.createStatement();
      26. }
      27. @Override
      28. public PreparedStatement prepareStatement(String sql) throws SQLException {
      29. return con.prepareStatement(sql);
      30. }
      31. @Override
      32. public CallableStatement prepareCall(String sql) throws SQLException {
      33. return con.prepareCall(sql);
      34. }
      35. @Override
      36. public String nativeSQL(String sql) throws SQLException {
      37. return con.nativeSQL(sql);
      38. }
      39. @Override
      40. public void setAutoCommit(boolean autoCommit) throws SQLException {
      41. con.setAutoCommit(autoCommit);
      42. }
      43. @Override
      44. public boolean getAutoCommit() throws SQLException {
      45. return con.getAutoCommit();
      46. }
      47. @Override
      48. public void commit() throws SQLException {
      49. con.commit();
      50. }
      51. @Override
      52. public void rollback() throws SQLException {
      53. con.rollback();
      54. }
      55. @Override
      56. public boolean isClosed() throws SQLException {
      57. return con.isClosed();
      58. }
      59. @Override
      60. public DatabaseMetaData getMetaData() throws SQLException {
      61. return con.getMetaData();
      62. }
      63. @Override
      64. public void setReadOnly(boolean readOnly) throws SQLException {
      65. con.setReadOnly(readOnly);
      66. }
      67. @Override
      68. public boolean isReadOnly() throws SQLException {
      69. return con.isReadOnly();
      70. }
      71. @Override
      72. public void setCatalog(String catalog) throws SQLException {
      73. con.setCatalog(catalog);
      74. }
      75. @Override
      76. public String getCatalog() throws SQLException {
      77. return con.getCatalog();
      78. }
      79. @Override
      80. public void setTransactionIsolation(int level) throws SQLException {
      81. con.setTransactionIsolation(level);
      82. }
      83. @Override
      84. public int getTransactionIsolation() throws SQLException {
      85. return con.getTransactionIsolation();
      86. }
      87. @Override
      88. public SQLWarning getWarnings() throws SQLException {
      89. return con.getWarnings();
      90. }
      91. @Override
      92. public void clearWarnings() throws SQLException {
      93. con.clearWarnings();
      94. }
      95. @Override
      96. public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
      97. return con.createStatement(resultSetType,resultSetConcurrency);
      98. }
      99. @Override
      100. public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
      101. return con.prepareStatement(sql,resultSetType,resultSetConcurrency);
      102. }
      103. @Override
      104. public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
      105. return con.prepareCall(sql,resultSetType,resultSetConcurrency);
      106. }
      107. @Override
      108. public Map> getTypeMap() throws SQLException {
      109. return con.getTypeMap();
      110. }
      111. @Override
      112. public void setTypeMap(Map> map) throws SQLException {
      113. con.setTypeMap(map);
      114. }
      115. @Override
      116. public void setHoldability(int holdability) throws SQLException {
      117. con.setHoldability(holdability);
      118. }
      119. @Override
      120. public int getHoldability() throws SQLException {
      121. return con.getHoldability();
      122. }
      123. @Override
      124. public Savepoint setSavepoint() throws SQLException {
      125. return con.setSavepoint();
      126. }
      127. @Override
      128. public Savepoint setSavepoint(String name) throws SQLException {
      129. return con.setSavepoint(name);
      130. }
      131. @Override
      132. public void rollback(Savepoint savepoint) throws SQLException {
      133. con.rollback(savepoint);
      134. }
      135. @Override
      136. public void releaseSavepoint(Savepoint savepoint) throws SQLException {
      137. con.releaseSavepoint(savepoint);
      138. }
      139. @Override
      140. public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
      141. return con.createStatement(resultSetType,resultSetConcurrency,resultSetHoldability);
      142. }
      143. @Override
      144. public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
      145. return con.prepareStatement(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
      146. }
      147. @Override
      148. public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
      149. return con.prepareCall(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
      150. }
      151. @Override
      152. public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
      153. return con.prepareStatement(sql,autoGeneratedKeys);
      154. }
      155. @Override
      156. public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
      157. return con.prepareStatement(sql,columnIndexes);
      158. }
      159. @Override
      160. public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
      161. return con.prepareStatement(sql,columnNames);
      162. }
      163. @Override
      164. public Clob createClob() throws SQLException {
      165. return con.createClob();
      166. }
      167. @Override
      168. public Blob createBlob() throws SQLException {
      169. return con.createBlob();
      170. }
      171. @Override
      172. public NClob createNClob() throws SQLException {
      173. return con.createNClob();
      174. }
      175. @Override
      176. public SQLXML createSQLXML() throws SQLException {
      177. return con.createSQLXML();
      178. }
      179. @Override
      180. public boolean isValid(int timeout) throws SQLException {
      181. return con.isValid(timeout);
      182. }
      183. @Override
      184. public void setClientInfo(String name, String value) throws SQLClientInfoException {
      185. con.setClientInfo(name,value);
      186. }
      187. @Override
      188. public void setClientInfo(Properties properties) throws SQLClientInfoException {
      189. con.setClientInfo(properties);
      190. }
      191. @Override
      192. public String getClientInfo(String name) throws SQLException {
      193. return con.getClientInfo(name);
      194. }
      195. @Override
      196. public Properties getClientInfo() throws SQLException {
      197. return con.getClientInfo();
      198. }
      199. @Override
      200. public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
      201. return con.createArrayOf(typeName,elements);
      202. }
      203. @Override
      204. public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
      205. return con.createStruct(typeName,attributes);
      206. }
      207. @Override
      208. public void setSchema(String schema) throws SQLException {
      209. con.setSchema(schema);
      210. }
      211. @Override
      212. public String getSchema() throws SQLException {
      213. return con.getSchema();
      214. }
      215. @Override
      216. public void abort(Executor executor) throws SQLException {
      217. con.abort(executor);
      218. }
      219. @Override
      220. public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
      221. con.setNetworkTimeout(executor,milliseconds);
      222. }
      223. @Override
      224. public int getNetworkTimeout() throws SQLException {
      225. return con.getNetworkTimeout();
      226. }
      227. @Override
      228. public T unwrap(Class iface) throws SQLException {
      229. return con.unwrap(iface);
      230. }
      231. @Override
      232. public boolean isWrapperFor(Class iface) throws SQLException {
      233. return con.isWrapperFor(iface);
      234. }
      235. }
      1. package demo02.myDataSourse;
      2. import demo02.utils.JDBCUtils;
      3. import javax.sql.DataSource;
      4. import java.io.PrintWriter;
      5. import java.sql.Connection;
      6. import java.sql.SQLException;
      7. import java.sql.SQLFeatureNotSupportedException;
      8. import java.util.ArrayList;
      9. import java.util.Collections;
      10. import java.util.List;
      11. import java.util.logging.Logger;
      12. //自定义数据库连接池
      13. public class demoDataSourse implements DataSource{
      14. //1.准备容器,用于保存多个连接对象
      15. private static List pool = Collections.synchronizedList(new ArrayList<>());
      16. //2.定义静态代码块,通过工具类获取10个连接对象
      17. static{
      18. for(int i=1;i<=10;i++){
      19. Connection con = JDBCUtils.getConnection();
      20. pool.add(con);
      21. }
      22. }
      23. //3.重写getConnection(),用于获取一个连接对象
      24. @Override
      25. public Connection getConnection() throws SQLException {
      26. if(pool.size()>0){
      27. Connection con = pool.remove(0);
      28. //通过自定义的连接对象,对原有的连接对象进行包装
      29. demomyConnection mycon = new demomyConnection(con,pool);
      30. return mycon;
      31. }else{
      32. throw new RuntimeException("连接数量已用尽");
      33. }
      34. }
      35. //4.定义getSize方法,获取连接池容器的大小
      36. public int getSize(){
      37. return pool.size();
      38. }
      39. @Override
      40. public Connection getConnection(String username, String password) throws SQLException {
      41. return null;
      42. }
      43. @Override
      44. public T unwrap(Class iface) throws SQLException {
      45. return null;
      46. }
      47. @Override
      48. public boolean isWrapperFor(Class iface) throws SQLException {
      49. return false;
      50. }
      51. @Override
      52. public PrintWriter getLogWriter() throws SQLException {
      53. return null;
      54. }
      55. @Override
      56. public void setLogWriter(PrintWriter out) throws SQLException {
      57. }
      58. @Override
      59. public void setLoginTimeout(int seconds) throws SQLException {
      60. }
      61. @Override
      62. public int getLoginTimeout() throws SQLException {
      63. return 0;
      64. }
      65. @Override
      66. public Logger getParentLogger() throws SQLFeatureNotSupportedException {
      67. return null;
      68. }
      69. }
      1. package demo02.myDataSourse;
      2. import java.sql.Connection;
      3. import java.sql.PreparedStatement;
      4. import java.sql.ResultSet;
      5. public class demoDataSourseTest {
      6. public static void main(String[] args) throws Exception {
      7. //1.创建连接池对象
      8. demoDataSourse dataSourse = new demoDataSourse();
      9. System.out.println("使用之前的数量" + dataSourse.getSize());
      10. //2.通过连接池对象获取连接对象
      11. Connection con = dataSourse.getConnection();
      12. //3.查询学生表的全部信息
      13. String sql = "SELECT * FROM student";
      14. PreparedStatement pst = con.prepareStatement(sql);
      15. //4.执行sql语句,接收结果集
      16. ResultSet rs = pst.executeQuery();
      17. //5.处理结果集
      18. while(rs.next()){
      19. System.out.println(rs.getInt("sid")+"\t"+rs.getString("name")+"\t"+rs.getInt("age")+"\t"+rs.getDate("birthday"));
      20. }
      21. //6.释放资源
      22. rs.close();
      23. pst.close();
      24. con.close();//用完以后,进行归还
      25. System.out.println("使用之后的数量" + dataSourse.getSize());
      26. }
      27. }
  • 相关阅读:
    eNSP学习——连接RIP与OSPF网络、默认路由
    抖音__ac_signature
    WPF中创建柱状图(数据统计)
    End-to-End Adversarial-Attention Network for Multi-Modal Clustering
    如何评价GPT-4o?
    Python吴恩达深度学习作业23 -- 机器翻译(NMT)
    office mac苹果办公软件安装包安装教程详解
    【Python】第六课 字典和集合
    星号倒三角
    短视频平台如何保证内容安全问题?
  • 原文地址:https://blog.csdn.net/weixin_59624686/article/details/126011249