JDBC自定义连接池过程详解

作者:海之浪子 时间:2023-11-17 13:27:55 

这篇文章主要介绍了JDBC自定义连接池过程详解,文中通过示例代码介绍的非常详细,对大家的学习或者工作具有一定的参考学习价值,需要的朋友可以参考下

开发中,"获得连接"和"释放资源"是非常消耗系统资源的,为了解决此类性能问题可以采用连接池技术来共享连接Connection。

1、概述

用池来管理Connection,这样可以重复使用Connection.这样我们就不用创建Connection,用池来管理Connection对象,当使用完Connection对象后,将Connection对象归还给池,这样后续还可以从池中获取Connection对象,可以重新再利用这个连接对象啦。

java为数据库连接池提供了公共接口:javax.sql.DataSource,各个厂商需要让自己的连接池实现这个接口。
常见的连接池:DBCP,C3P0

2、自定义连接池

编写自定义连接池

1、创建连接池并实现接口javax.sql.DataSource,并使用接口中的getConnection()方法

2、提供一个集合,用于存放连接,可以采用LinkedList

3、后面程序如果需要,可以调用实现类getConnection(),并从list中获取链接。为保证当前连接只能提供给一个线程使用,所以我们需要将连接先从连接池中移除

4、当用户用完连接后,将连接归还到连接池中

3、自定义连接池采用装饰者设计模式


public class ConnectionPool implements Connection {

private Connection connection;
 private LinkedList<Connection> pool;

public ConnectionPool(Connection connection, LinkedList<Connection> pool){
   this.connection=connection;
   this.pool=pool;
 }

@Override
 public PreparedStatement prepareStatement(String sql) throws SQLException {
   return connection.prepareStatement(sql);
 }

@Override
 public void close() throws SQLException {
   pool.add(connection);

}
 @Override
 public Statement createStatement() throws SQLException {
   return null;
 }

@Override
 public CallableStatement prepareCall(String sql) throws SQLException {
   return null;
 }

@Override
 public String nativeSQL(String sql) throws SQLException {
   return null;
 }

@Override
 public void setAutoCommit(boolean autoCommit) throws SQLException {

}

@Override
 public boolean getAutoCommit() throws SQLException {
   return false;
 }

@Override
 public void commit() throws SQLException {

}

@Override
 public void rollback() throws SQLException {

}

@Override
 public boolean isClosed() throws SQLException {
   return false;
 }

@Override
 public DatabaseMetaData getMetaData() throws SQLException {
   return null;
 }

@Override
 public void setReadOnly(boolean readOnly) throws SQLException {

}

@Override
 public boolean isReadOnly() throws SQLException {
   return false;
 }

@Override
 public void setCatalog(String catalog) throws SQLException {

}

@Override
 public String getCatalog() throws SQLException {
   return null;
 }

@Override
 public void setTransactionIsolation(int level) throws SQLException {

}

@Override
 public int getTransactionIsolation() throws SQLException {
   return 0;
 }

@Override
 public SQLWarning getWarnings() throws SQLException {
   return null;
 }

@Override
 public void clearWarnings() throws SQLException {

}

@Override
 public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
   return null;
 }

@Override
 public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
   return null;
 }

@Override
 public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
   return null;
 }

@Override
 public Map<String, Class<?>> getTypeMap() throws SQLException {
   return null;
 }

@Override
 public void setTypeMap(Map<String, Class<?>> map) throws SQLException {

}

@Override
 public void setHoldability(int holdability) throws SQLException {

}

@Override
 public int getHoldability() throws SQLException {
   return 0;
 }

@Override
 public Savepoint setSavepoint() throws SQLException {
   return null;
 }

@Override
 public Savepoint setSavepoint(String name) throws SQLException {
   return null;
 }

@Override
 public void rollback(Savepoint savepoint) throws SQLException {

}

@Override
 public void releaseSavepoint(Savepoint savepoint) throws SQLException {

}

@Override
 public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
   return null;
 }

@Override
 public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
   return null;
 }

@Override
 public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
   return null;
 }

@Override
 public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
   return null;
 }

@Override
 public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
   return null;
 }

@Override
 public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
   return null;
 }

@Override
 public Clob createClob() throws SQLException {
   return null;
 }

@Override
 public Blob createBlob() throws SQLException {
   return null;
 }

@Override
 public NClob createNClob() throws SQLException {
   return null;
 }

@Override
 public SQLXML createSQLXML() throws SQLException {
   return null;
 }

@Override
 public boolean isValid(int timeout) throws SQLException {
   return false;
 }

@Override
 public void setClientInfo(String name, String value) throws SQLClientInfoException {

}

@Override
 public void setClientInfo(Properties properties) throws SQLClientInfoException {

}

@Override
 public String getClientInfo(String name) throws SQLException {
   return null;
 }

@Override
 public Properties getClientInfo() throws SQLException {
   return null;
 }

@Override
 public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
   return null;
 }

@Override
 public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
   return null;
 }

@Override
 public void setSchema(String schema) throws SQLException {

}

@Override
 public String getSchema() throws SQLException {
   return null;
 }

@Override
 public void abort(Executor executor) throws SQLException {

}

@Override
 public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {

}

@Override
 public int getNetworkTimeout() throws SQLException {
   return 0;
 }

@Override
 public <T> T unwrap(Class<T> iface) throws SQLException {
   return null;
 }

@Override
 public boolean isWrapperFor(Class<?> iface) throws SQLException {
   return false;
 }
}

DataSourcePool


public class DataSourcePool implements DataSource {
 //1.创建1个容器用于存储Connection对象
 private static LinkedList<Connection> pool = new LinkedList<Connection>();

//2.创建5个连接放到容器中去
 static{
   for (int i = 0; i < 5; i++) {
     Connection conn = JDBCUtils.getConnection();
     //放入池子中connection对象已经经过改造了
     ConnectionPool connectionPool = new ConnectionPool(conn, pool);
     pool.add(connectionPool);
   }
 }

/**
  * 重写获取连接的方法
  */
 @Override
 public Connection getConnection() throws SQLException {
   Connection conn = null;
   //3.使用前先判断
   if(pool.size()==0){
     //4.池子里面没有,我们再创建一些
     for (int i = 0; i < 5; i++) {
       conn = JDBCUtils.getConnection();
       //放入池子中connection对象已经经过改造了
       ConnectionPool connectionPool = new ConnectionPool(conn, pool);
       pool.add(connectionPool);
     }
   }
   //5.从池子里面获取一个连接对象Connection
   conn = pool.remove(0);
   return conn;
 }

@Override
 public Connection getConnection(String username, String password) throws SQLException {
   return null;
 }

@Override
 public <T> T unwrap(Class<T> iface) throws SQLException {
   return null;
 }

@Override
 public boolean isWrapperFor(Class<?> iface) throws SQLException {
   return false;
 }

@Override
 public PrintWriter getLogWriter() throws SQLException {
   return null;
 }

@Override
 public void setLogWriter(PrintWriter out) throws SQLException {

}

@Override
 public void setLoginTimeout(int seconds) throws SQLException {

}

@Override
 public int getLoginTimeout() throws SQLException {
   return 0;
 }

@Override
 public Logger getParentLogger() throws SQLFeatureNotSupportedException {
   return null;
 }
}

测试代码如下


@Test
 public void test1(){
   Connection conn = null;
   PreparedStatement pstmt = null;
   // 1.创建自定义连接池对象
   DataSource dataSource = new DataSourcePool();
   try {
     // 2.从池子中获取连接
     conn = dataSource.getConnection();
     String sql = "insert into USER values(?,?)";
     //3.必须在自定义的connection类中重写prepareStatement(sql)方法
     pstmt = conn.prepareStatement(sql);
     pstmt.setString(1, "李四");
     pstmt.setString(2, "1234");
     int rows = pstmt.executeUpdate();
     System.out.println("rows:"+rows);
   } catch (Exception e) {
     throw new RuntimeException(e);
   } finally {
     JDBCUtils.relase(conn, pstmt, null);
   }
 }

来源:https://www.cnblogs.com/haizhilangzi/p/10909089.html

标签:JDBC,连接,池
0
投稿

猜你喜欢

  • C#序列化成XML注意细节

    2023-04-20 01:07:00
  • java8 Stream list to Map key 重复 value合并到Collectio的操作

    2022-02-01 23:53:58
  • 浅谈java 面对对象(抽象 继承 接口 多态)

    2022-04-01 07:23:50
  • UnityShader使用Plane实现翻书效果

    2022-05-19 14:46:14
  • C#使用DevExpress中的XtraCharts控件实现图表

    2022-12-21 10:14:10
  • JavaWeb验证码校验功能代码实例

    2022-07-18 23:46:52
  • 微信第三方登录Android实现代码

    2023-07-27 08:05:49
  • Java后台批量生产echarts图表并保存图片

    2023-11-25 03:24:39
  • C#的FileInfo类实现文件操作实例

    2021-06-30 06:39:44
  • 详解Java类库的概念以及import的使用方法

    2022-04-18 06:56:54
  • C#采用HttpWebRequest实现保持会话上传文件到HTTP的方法

    2023-07-18 17:20:29
  • Android稳定性:可远程配置化的Looper兜底框架

    2022-02-18 09:02:23
  • Flutter TV Android端开发技巧详细教程

    2021-09-16 20:32:18
  • C#反射调用dll文件中的方法操作泛型与属性字段

    2022-09-15 03:24:04
  • C#打包应用程序,与.NETFramework介绍

    2022-03-29 15:29:20
  • Springboot过滤器禁止ip频繁访问功能实现

    2022-08-29 11:20:59
  • Maven项目读取resources文件路径问题解决方案

    2023-04-21 15:05:11
  • Java中String类常用方法总结详解

    2022-03-06 04:50:58
  • 阿里云发布 Spring Boot 新脚手架工程

    2023-10-08 04:43:12
  • Java线程同步方法实例总结

    2022-08-20 20:35:08
  • asp之家 软件编程 m.aspxhome.com