MyDataSource实现封装连接池,MyConnection实现connection类,通过代理模式相互调用

package cn.itcast;

import java.sql.*;

public class ConnectDemo {

	public static void main(String[] args) throws Exception {
for(int i=0;i<21;i++){
Connection conn = JdbcUtils.getConnection();
System.out.println(conn);
JdbcUtils.free(null, null, conn);
}
} }
package cn.itcast;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement; import cn.itcast.datasource.DataSourceDemo1; public final class JdbcUtils { // private static String url = "jdbc:mysql://";
// private static String user = "";
// private static String password = ""; private static MyDataSource mydatasource = null; public JdbcUtils() {
} static {
try {
Class.forName("com.mysql.jdbc.Driver");
mydatasource = new MyDataSource();
} catch (ClassNotFoundException e) {
// TODO Auto-generated catch block
throw new ExceptionInInitializerError(e);
}
} public static Connection getConnection() throws SQLException {
return mydatasource.getConnection();
} public static void free(ResultSet rs, Statement st, Connection conn) {
try {
if (rs != null)
rs.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
try {
if (st != null)
st.close();
} catch (SQLException e) {
e.printStackTrace();
} finally {
if (conn != null)
try {
conn.close();
// mydatasource.free(conn);
} catch (Exception e) {
e.printStackTrace();
}
}
}
}
}
package cn.itcast;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.LinkedList; public class MyDataSource { private static String url = "jdbc:mysql://";
private static String user = "";
private static String password = ""; // 初始化连接数
private static int initCount = 5;
//最大创建数
private static int maxCount = 10;
int currentCount = 0; public LinkedList<Connection> connectionsPool = new LinkedList<Connection>(); public MyDataSource() {
for (int i = 0; i < initCount; i++) {
try {
this.connectionsPool.addLast(this.createConnection());
this.currentCount++;
} catch (SQLException e) {
throw new ExceptionInInitializerError(e);
}
}
} public Connection getConnection() throws SQLException { synchronized (connectionsPool) {
if (this.connectionsPool.size() > 0) {
return this.connectionsPool.removeFirst();
} else if (this.currentCount < maxCount) {
this.currentCount++;
return this.createConnection();
} else {
throw new SQLException("超过最大连接数量");
} }
} public void free(Connection conn) {
this.connectionsPool.addLast(conn);
} private Connection createConnection() throws SQLException {
Connection realConn = DriverManager.getConnection(url, user, password);
MyConnection myConnection = new MyConnection(realConn, this);
return myConnection;
}
}
package cn.itcast;

import java.sql.Array;
import java.sql.Blob;
import java.sql.CallableStatement;
import java.sql.Clob;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.NClob;
import java.sql.PreparedStatement;
import java.sql.SQLClientInfoException;
import java.sql.SQLException;
import java.sql.SQLWarning;
import java.sql.SQLXML;
import java.sql.Savepoint;
import java.sql.Statement;
import java.sql.Struct;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor; import cn.itcast.datasource.DataSourceDemo1; public class MyConnection implements Connection {
private Connection realConnection;
private MyDataSource dataSource;
//连接最大使用次数
private int maxUseCount = 10;
//当前使用次数
private int currentUserCount = 0; MyConnection(Connection connection, MyDataSource datasource) {
this.realConnection = connection;
this.dataSource = datasource;
} @Override
public void close() throws SQLException {
// TODO Auto-generated method stub
this.currentUserCount++;
if (this.currentUserCount > this.maxUseCount)
this.dataSource.connectionsPool.addLast(this);
else { this.realConnection.close();// 真正关掉
this.dataSource.currentCount--;
}
} @Override
public <T> T unwrap(Class<T> iface) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public Statement createStatement() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public CallableStatement prepareCall(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public String nativeSQL(String sql) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
// TODO Auto-generated method stub } @Override
public boolean getAutoCommit() throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public void commit() throws SQLException {
// TODO Auto-generated method stub
this.realConnection.commit();
} @Override
public void rollback() throws SQLException {
// TODO Auto-generated method stub } @Override
public boolean isClosed() throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public DatabaseMetaData getMetaData() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setReadOnly(boolean readOnly) throws SQLException {
// TODO Auto-generated method stub } @Override
public boolean isReadOnly() throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public void setCatalog(String catalog) throws SQLException {
// TODO Auto-generated method stub } @Override
public String getCatalog() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setTransactionIsolation(int level) throws SQLException {
// TODO Auto-generated method stub } @Override
public int getTransactionIsolation() throws SQLException {
// TODO Auto-generated method stub
return 0;
} @Override
public SQLWarning getWarnings() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void clearWarnings() throws SQLException {
// TODO Auto-generated method stub
this.realConnection.clearWarnings();
} @Override
public Statement createStatement(int resultSetType, int resultSetConcurrency)
throws SQLException {
// TODO Auto-generated method stub
return this.realConnection.createStatement();
} @Override
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
// TODO Auto-generated method stub } @Override
public void setHoldability(int holdability) throws SQLException {
// TODO Auto-generated method stub } @Override
public int getHoldability() throws SQLException {
// TODO Auto-generated method stub
return 0;
} @Override
public Savepoint setSavepoint() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Savepoint setSavepoint(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void rollback(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub } @Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
// TODO Auto-generated method stub } @Override
public Statement createStatement(int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public PreparedStatement prepareStatement(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public CallableStatement prepareCall(String sql, int resultSetType,
int resultSetConcurrency, int resultSetHoldability)
throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)
throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes)
throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public PreparedStatement prepareStatement(String sql, String[] columnNames)
throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Clob createClob() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Blob createBlob() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public NClob createNClob() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public SQLXML createSQLXML() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public boolean isValid(int timeout) throws SQLException {
// TODO Auto-generated method stub
return false;
} @Override
public void setClientInfo(String name, String value)
throws SQLClientInfoException {
// TODO Auto-generated method stub } @Override
public void setClientInfo(Properties properties)
throws SQLClientInfoException {
// TODO Auto-generated method stub } @Override
public String getClientInfo(String name) throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Properties getClientInfo() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Array createArrayOf(String typeName, Object[] elements)
throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public Struct createStruct(String typeName, Object[] attributes)
throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void setSchema(String schema) throws SQLException {
// TODO Auto-generated method stub } @Override
public String getSchema() throws SQLException {
// TODO Auto-generated method stub
return null;
} @Override
public void abort(Executor executor) throws SQLException {
// TODO Auto-generated method stub } @Override
public void setNetworkTimeout(Executor executor, int milliseconds)
throws SQLException {
// TODO Auto-generated method stub } @Override
public int getNetworkTimeout() throws SQLException {
// TODO Auto-generated method stub
return 0;
} }

java_jdbc_基本连接池的更多相关文章

  1. 用Swoole4 打造高并发的PHP协程Mysql连接池

    码云代码仓库:https://gitee.com/tanjiajun/MysqlPool 代码仓库:https://github.com/asbectJ/swoole4.git 前言 在写这篇文章之前 ...

  2. JDBC第三次学习

    这是我的JDBC第三次学习了,在学习的过程中,老是会忘掉一些知识,不记下笔记实在不行啊! 使用JDBC调用存储过程 (1)关于如何使用Navicat(11.1.13) for MySQL如何创建存储过 ...

  3. 22Java之JDBCTemplate总结

    写在前面:这里总结4种方式来操作数据库(SE阶段) 一.JDBC         JDBC有关的类:都在java.sql 和 javax.sql 包下.   1.数据准备               ...

  4. 传智播客JDBC视频教程

    视频介绍: 一些视频教程通过浅显案例来让刚開始学习的人感到轻松,可是课程中编写的代码不能直接应用于项目中:而本套视频教程正好相反,视频解说者李勇老师以技术见长.性格朴实无华.不善于幽默搞笑.李勇老师编 ...

  5. JDBC连接池(数据源)

    自定义连接池:用装饰设计模式将原连接的close方法改造成将连接还回数据源:装饰设计模式:http://www.cnblogs.com/tongxuping/p/6832518.html: 开源数据库 ...

  6. Spring系列 之数据源的配置 数据库 数据源 连接池的区别

    Spring系列之数据源的配置 数据源,连接池,数据库三者的区别 连接池:这个应该都学习过,比如c3p0,druid等等,连接池的作用是为了提高程序的效率,因为频繁的去创建,关闭数据库连接,会对性能有 ...

  7. 【springboot】集成Druid 作为数据库连接池

    转自:https://blog.csdn.net/cp026la/article/details/86508139 1. 引言 用户的每一次请求几乎都会访问数据库,访问数据库需要向数据库获取链接,而数 ...

  8. 多线程爬坑之路-学习多线程需要来了解哪些东西?(concurrent并发包的数据结构和线程池,Locks锁,Atomic原子类)

    前言:刚学习了一段机器学习,最近需要重构一个java项目,又赶过来看java.大多是线程代码,没办法,那时候总觉得多线程是个很难的部分很少用到,所以一直没下决定去啃,那些年留下的坑,总是得自己跳进去填 ...

  9. C#多线程之线程池篇3

    在上一篇C#多线程之线程池篇2中,我们主要学习了线程池和并行度以及如何实现取消选项的相关知识.在这一篇中,我们主要学习如何使用等待句柄和超时.使用计时器和使用BackgroundWorker组件的相关 ...

随机推荐

  1. maven pom.xml加载不同properties配置

    1.pom.xml =========================== <!-- 不同的打包环境配置: test=开发/测试测试环境,  product=生产环境; 命令行方式: mvn c ...

  2. 安装ejabberd2并配置MySQL为其数据库

    以前用过openfire做为服务器,但是openfire的集群支持不是很好,所以改用Ejabberd,由于它是用Erlang语言开发的,其并发率与分布式的功能都是很强悍的,在此我记录一下我的安装与配置 ...

  3. unix network programming(3rd)Vol.1 [第2~5章]《读书笔记系列》

    13~22章 重要 第2章 传输层: TCP/ UDP / STCP (Stream Control Transmission Protocol) TCP 可靠,有重传机制,SYN队列号 UDP 不可 ...

  4. Hbase 建表基本命令总结

    访问hbase,以及操作hbase,命令不用使用分号 hbase shell 进入hbase list 查看表 hbase shell -d hbase(main):024:0> scan '. ...

  5. 【Python】Python-用大写字母打印你的名字

    与孩子一起编程,有个作业题:用大写字母打印你的名字. CCCC A RRRRR C C A A R R C A A R R C AAAAAAA RRRRR C C A A R R CCCC A A R ...

  6. HDU 5696 区间的价值 暴力

    分析:枚举以该点为最小值,然后找到最大值,更新,相应数组,至此,把区间分割(因为包含这个最小值点已经枚举过) 然后理解理解,感觉好像挺对的...因为后面(即dfs区间变小时)如果再包含最小值节点,也不 ...

  7. unity3d教程资源

    unity2d教程网 http://learnunity2d.com/2d-shootem-up-tutorial/ 横版射击2d游戏系列教程 http://pixelnest.io/tutorial ...

  8. MFC控件

    控件的通知消息 控件的消息映射宏的格式大致是: ON_通知消息码(nID, memberFun) //nID参数是控件的ID,memberFun参数是消息处理函数名.例如,ON_BN_CLICKED( ...

  9. 导入showb时候出错--2015-12-4

    [root@cache-02 ~]# /opt/coreseek/csftweb-bash: /opt/coreseek/csftweb: is a directory[root@cache-02 ~ ...

  10. Eclipse(非J2EE版本)配置Extjs环境以及安装部署Tomcat

    Eclipse(非J2EE版本)配置Extjs环境(Spket) 1. 安装spket插件,帮助->安装新软件->http://www.agpad.com/update. 2. 设置Spk ...