自定义连接池
主類:
package star.july.dataSource;import java.sql.Connection;
import java.sql.SQLException;public class MyDao {public static void main(String[] args) throws SQLException {//創(chuàng)建連接池程序MyDataSource ds = new MyDataSource();for(int i =1; i<=11;i++){//從連接池程序獲取對(duì)象Connection conn = ds.getConnection();System.out.println(conn);//模擬第三個(gè)用戶釋放了連接if(i ==1){//使用回Connection.close()方法釋放鏈接//問(wèn)題:close()方法原來(lái)并不是連接放回連接池,而是關(guān)閉連接//解決方法:讓close()能夠?qū)崿F(xiàn)放回連接池的功能//即用代理方法包裝類conn.close();} }}
}
自定義連接池: package star.july.dataSource;import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.LinkedList; import java.util.logging.Logger;import javax.sql.DataSource;//自定義連接池public class MyDataSource implements DataSource{private static String driverClass = "com.mysql.jdbc.Driver";private static String url = "jdbc:mysql://localhost:3306/day18";private static String user = "root";private static String password = "root";//設(shè)計(jì)一個(gè)集合用于存放連接對(duì)象private static LinkedList<Connection> pool = new LinkedList<Connection>();//初始化連接數(shù)private int initConn = 5;//數(shù)據(jù)庫(kù)能夠承受的最大連接數(shù)private int maxConn = 10;//用于記錄連接池一共提供了多少個(gè)連接數(shù)private int curConn = 0;//當(dāng)初始化連接池程序的時(shí)候,就已經(jīng)初始化了若干個(gè)對(duì)象public MyDataSource(){//創(chuàng)建5個(gè)連接對(duì)象,放入集合中for(int i =1 ; i <= initConn; i ++){curConn++;pool.add(createConnection());}}static{//注冊(cè)驅(qū)動(dòng)try{Class.forName(driverClass);}catch(ClassNotFoundException e){e.printStackTrace();}}//創(chuàng)建一個(gè)連接對(duì)象的方法public Connection createConnection(){try{//被代理類對(duì)象Connection conn = DriverManager.getConnection(url,user,password);//創(chuàng)建代理類對(duì)象MyConnectionProxy proxy = new MyConnectionProxy(conn,this);return proxy; }catch(SQLException e){ e.printStackTrace();throw new RuntimeException();}}//這個(gè)方法提供給外部程序獲取連接對(duì)象的@Overridepublic Connection getConnection() throws SQLException {//情況1:并發(fā)連接數(shù)小于等于初始化連接數(shù)的時(shí)候,直接初始化連接取出即可if(pool.size()>0){Connection conn = pool.removeLast();return conn;}//情況2:并發(fā)連接數(shù)大于初始連接數(shù)且小于最大連接數(shù),重新再創(chuàng)建新的鏈接給用戶if(curConn<maxConn){curConn++;return createConnection();}//情況3:并發(fā)連接數(shù)大于最大連接數(shù)時(shí),不能再提供連接數(shù)throw new RuntimeException();}//釋放連接,把連接放回連接池程序public void releaseConnection(Connection conn){pool.addLast(conn);}@Overridepublic PrintWriter getLogWriter() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setLogWriter(PrintWriter out) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setLoginTimeout(int seconds) throws SQLException {// TODO Auto-generated method stub}@Overridepublic int getLoginTimeout() throws SQLException {// TODO Auto-generated method stubreturn 0;}@Overridepublic Logger getParentLogger() throws SQLFeatureNotSupportedException {// TODO Auto-generated method stubreturn null;}@Overridepublic <T> T unwrap(Class<T> iface) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic boolean isWrapperFor(Class<?> iface) throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic Connection getConnection(String username, String password)throws SQLException {// TODO Auto-generated method stubreturn null;}}
連接對(duì)象的代理類
package star.july.dataSource;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;/*** 連接對(duì)象的代理類*/ public class MyConnectionProxy implements Connection{private Connection realConn;private MyDataSource ds;//接收被代理類對(duì)象(JDBC4Connection)public MyConnectionProxy(Connection conn,MyDataSource ds){this.realConn = conn;this.ds = ds;}@Overridepublic void close() throws SQLException {//改寫:把連接放回連接池//調(diào)用連接池釋放連接的方法ds.releaseConnection(realConn);}@Overridepublic <T> T unwrap(Class<T> iface) throws SQLException {return realConn.unwrap(iface);}@Overridepublic boolean isWrapperFor(Class<?> iface) throws SQLException {return realConn.isWrapperFor(iface);}@Overridepublic Statement createStatement() throws SQLException {return realConn.createStatement();}@Overridepublic PreparedStatement prepareStatement(String sql) throws SQLException {return null;}@Overridepublic CallableStatement prepareCall(String sql) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic String nativeSQL(String sql) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setAutoCommit(boolean autoCommit) throws SQLException {// TODO Auto-generated method stub}@Overridepublic boolean getAutoCommit() throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic void commit() throws SQLException {// TODO Auto-generated method stub}@Overridepublic void rollback() throws SQLException {// TODO Auto-generated method stub}@Overridepublic boolean isClosed() throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic DatabaseMetaData getMetaData() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setReadOnly(boolean readOnly) throws SQLException {// TODO Auto-generated method stub}@Overridepublic boolean isReadOnly() throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic void setCatalog(String catalog) throws SQLException {// TODO Auto-generated method stub}@Overridepublic String getCatalog() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setTransactionIsolation(int level) throws SQLException {// TODO Auto-generated method stub}@Overridepublic int getTransactionIsolation() throws SQLException {// TODO Auto-generated method stubreturn 0;}@Overridepublic SQLWarning getWarnings() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void clearWarnings() throws SQLException {// TODO Auto-generated method stub}@Overridepublic Statement createStatement(int resultSetType, int resultSetConcurrency)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String sql, int resultSetType,int resultSetConcurrency) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic CallableStatement prepareCall(String sql, int resultSetType,int resultSetConcurrency) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Map<String, Class<?>> getTypeMap() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setTypeMap(Map<String, Class<?>> map) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setHoldability(int holdability) throws SQLException {// TODO Auto-generated method stub}@Overridepublic int getHoldability() throws SQLException {// TODO Auto-generated method stubreturn 0;}@Overridepublic Savepoint setSavepoint() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Savepoint setSavepoint(String name) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void rollback(Savepoint savepoint) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void releaseSavepoint(Savepoint savepoint) throws SQLException {// TODO Auto-generated method stub}@Overridepublic Statement createStatement(int resultSetType,int resultSetConcurrency, int resultSetHoldability)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String sql, int resultSetType,int resultSetConcurrency, int resultSetHoldability)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic CallableStatement prepareCall(String sql, int resultSetType,int resultSetConcurrency, int resultSetHoldability)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String sql, int[] columnIndexes)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String sql, String[] columnNames)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Clob createClob() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Blob createBlob() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic NClob createNClob() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic SQLXML createSQLXML() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic boolean isValid(int timeout) throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic void setClientInfo(String name, String value)throws SQLClientInfoException {// TODO Auto-generated method stub}@Overridepublic void setClientInfo(Properties properties)throws SQLClientInfoException {// TODO Auto-generated method stub}@Overridepublic String getClientInfo(String name) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Properties getClientInfo() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Array createArrayOf(String typeName, Object[] elements)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Struct createStruct(String typeName, Object[] attributes)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setSchema(String schema) throws SQLException {// TODO Auto-generated method stub}@Overridepublic String getSchema() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void abort(Executor executor) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setNetworkTimeout(Executor executor, int milliseconds)throws SQLException {// TODO Auto-generated method stub}@Overridepublic int getNetworkTimeout() throws SQLException {// TODO Auto-generated method stubreturn 0;}}
自定義連接池: package star.july.dataSource;import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.LinkedList; import java.util.logging.Logger;import javax.sql.DataSource;//自定義連接池public class MyDataSource implements DataSource{private static String driverClass = "com.mysql.jdbc.Driver";private static String url = "jdbc:mysql://localhost:3306/day18";private static String user = "root";private static String password = "root";//設(shè)計(jì)一個(gè)集合用于存放連接對(duì)象private static LinkedList<Connection> pool = new LinkedList<Connection>();//初始化連接數(shù)private int initConn = 5;//數(shù)據(jù)庫(kù)能夠承受的最大連接數(shù)private int maxConn = 10;//用于記錄連接池一共提供了多少個(gè)連接數(shù)private int curConn = 0;//當(dāng)初始化連接池程序的時(shí)候,就已經(jīng)初始化了若干個(gè)對(duì)象public MyDataSource(){//創(chuàng)建5個(gè)連接對(duì)象,放入集合中for(int i =1 ; i <= initConn; i ++){curConn++;pool.add(createConnection());}}static{//注冊(cè)驅(qū)動(dòng)try{Class.forName(driverClass);}catch(ClassNotFoundException e){e.printStackTrace();}}//創(chuàng)建一個(gè)連接對(duì)象的方法public Connection createConnection(){try{//被代理類對(duì)象Connection conn = DriverManager.getConnection(url,user,password);//創(chuàng)建代理類對(duì)象MyConnectionProxy proxy = new MyConnectionProxy(conn,this);return proxy; }catch(SQLException e){ e.printStackTrace();throw new RuntimeException();}}//這個(gè)方法提供給外部程序獲取連接對(duì)象的@Overridepublic Connection getConnection() throws SQLException {//情況1:并發(fā)連接數(shù)小于等于初始化連接數(shù)的時(shí)候,直接初始化連接取出即可if(pool.size()>0){Connection conn = pool.removeLast();return conn;}//情況2:并發(fā)連接數(shù)大于初始連接數(shù)且小于最大連接數(shù),重新再創(chuàng)建新的鏈接給用戶if(curConn<maxConn){curConn++;return createConnection();}//情況3:并發(fā)連接數(shù)大于最大連接數(shù)時(shí),不能再提供連接數(shù)throw new RuntimeException();}//釋放連接,把連接放回連接池程序public void releaseConnection(Connection conn){pool.addLast(conn);}@Overridepublic PrintWriter getLogWriter() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setLogWriter(PrintWriter out) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setLoginTimeout(int seconds) throws SQLException {// TODO Auto-generated method stub}@Overridepublic int getLoginTimeout() throws SQLException {// TODO Auto-generated method stubreturn 0;}@Overridepublic Logger getParentLogger() throws SQLFeatureNotSupportedException {// TODO Auto-generated method stubreturn null;}@Overridepublic <T> T unwrap(Class<T> iface) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic boolean isWrapperFor(Class<?> iface) throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic Connection getConnection(String username, String password)throws SQLException {// TODO Auto-generated method stubreturn null;}}
連接對(duì)象的代理類
package star.july.dataSource;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;/*** 連接對(duì)象的代理類*/ public class MyConnectionProxy implements Connection{private Connection realConn;private MyDataSource ds;//接收被代理類對(duì)象(JDBC4Connection)public MyConnectionProxy(Connection conn,MyDataSource ds){this.realConn = conn;this.ds = ds;}@Overridepublic void close() throws SQLException {//改寫:把連接放回連接池//調(diào)用連接池釋放連接的方法ds.releaseConnection(realConn);}@Overridepublic <T> T unwrap(Class<T> iface) throws SQLException {return realConn.unwrap(iface);}@Overridepublic boolean isWrapperFor(Class<?> iface) throws SQLException {return realConn.isWrapperFor(iface);}@Overridepublic Statement createStatement() throws SQLException {return realConn.createStatement();}@Overridepublic PreparedStatement prepareStatement(String sql) throws SQLException {return null;}@Overridepublic CallableStatement prepareCall(String sql) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic String nativeSQL(String sql) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setAutoCommit(boolean autoCommit) throws SQLException {// TODO Auto-generated method stub}@Overridepublic boolean getAutoCommit() throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic void commit() throws SQLException {// TODO Auto-generated method stub}@Overridepublic void rollback() throws SQLException {// TODO Auto-generated method stub}@Overridepublic boolean isClosed() throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic DatabaseMetaData getMetaData() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setReadOnly(boolean readOnly) throws SQLException {// TODO Auto-generated method stub}@Overridepublic boolean isReadOnly() throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic void setCatalog(String catalog) throws SQLException {// TODO Auto-generated method stub}@Overridepublic String getCatalog() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setTransactionIsolation(int level) throws SQLException {// TODO Auto-generated method stub}@Overridepublic int getTransactionIsolation() throws SQLException {// TODO Auto-generated method stubreturn 0;}@Overridepublic SQLWarning getWarnings() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void clearWarnings() throws SQLException {// TODO Auto-generated method stub}@Overridepublic Statement createStatement(int resultSetType, int resultSetConcurrency)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String sql, int resultSetType,int resultSetConcurrency) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic CallableStatement prepareCall(String sql, int resultSetType,int resultSetConcurrency) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Map<String, Class<?>> getTypeMap() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setTypeMap(Map<String, Class<?>> map) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setHoldability(int holdability) throws SQLException {// TODO Auto-generated method stub}@Overridepublic int getHoldability() throws SQLException {// TODO Auto-generated method stubreturn 0;}@Overridepublic Savepoint setSavepoint() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Savepoint setSavepoint(String name) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void rollback(Savepoint savepoint) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void releaseSavepoint(Savepoint savepoint) throws SQLException {// TODO Auto-generated method stub}@Overridepublic Statement createStatement(int resultSetType,int resultSetConcurrency, int resultSetHoldability)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String sql, int resultSetType,int resultSetConcurrency, int resultSetHoldability)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic CallableStatement prepareCall(String sql, int resultSetType,int resultSetConcurrency, int resultSetHoldability)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String sql, int autoGeneratedKeys)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String sql, int[] columnIndexes)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String sql, String[] columnNames)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Clob createClob() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Blob createBlob() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic NClob createNClob() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic SQLXML createSQLXML() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic boolean isValid(int timeout) throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic void setClientInfo(String name, String value)throws SQLClientInfoException {// TODO Auto-generated method stub}@Overridepublic void setClientInfo(Properties properties)throws SQLClientInfoException {// TODO Auto-generated method stub}@Overridepublic String getClientInfo(String name) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Properties getClientInfo() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Array createArrayOf(String typeName, Object[] elements)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Struct createStruct(String typeName, Object[] attributes)throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setSchema(String schema) throws SQLException {// TODO Auto-generated method stub}@Overridepublic String getSchema() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void abort(Executor executor) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setNetworkTimeout(Executor executor, int milliseconds)throws SQLException {// TODO Auto-generated method stub}@Overridepublic int getNetworkTimeout() throws SQLException {// TODO Auto-generated method stubreturn 0;}}
總結(jié)
- 上一篇: JDBC进阶:调用数据库,将文件或其他字
- 下一篇: D3P0实践小例子