自定义连接池
主類:
package star.july.dataSource;import java.sql.Connection;
import java.sql.SQLException;public class MyDao {public static void main(String[] args) throws SQLException {//創建連接池程序MyDataSource ds = new MyDataSource();for(int i =1; i<=11;i++){//從連接池程序獲取對象Connection conn = ds.getConnection();System.out.println(conn);//模擬第三個用戶釋放了連接if(i ==1){//使用回Connection.close()方法釋放鏈接//問題:close()方法原來并不是連接放回連接池,而是關閉連接//解決方法:讓close()能夠實現放回連接池的功能//即用代理方法包裝類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";//設計一個集合用于存放連接對象private static LinkedList<Connection> pool = new LinkedList<Connection>();//初始化連接數private int initConn = 5;//數據庫能夠承受的最大連接數private int maxConn = 10;//用于記錄連接池一共提供了多少個連接數private int curConn = 0;//當初始化連接池程序的時候,就已經初始化了若干個對象public MyDataSource(){//創建5個連接對象,放入集合中for(int i =1 ; i <= initConn; i ++){curConn++;pool.add(createConnection());}}static{//注冊驅動try{Class.forName(driverClass);}catch(ClassNotFoundException e){e.printStackTrace();}}//創建一個連接對象的方法public Connection createConnection(){try{//被代理類對象Connection conn = DriverManager.getConnection(url,user,password);//創建代理類對象MyConnectionProxy proxy = new MyConnectionProxy(conn,this);return proxy; }catch(SQLException e){ e.printStackTrace();throw new RuntimeException();}}//這個方法提供給外部程序獲取連接對象的@Overridepublic Connection getConnection() throws SQLException {//情況1:并發連接數小于等于初始化連接數的時候,直接初始化連接取出即可if(pool.size()>0){Connection conn = pool.removeLast();return conn;}//情況2:并發連接數大于初始連接數且小于最大連接數,重新再創建新的鏈接給用戶if(curConn<maxConn){curConn++;return createConnection();}//情況3:并發連接數大于最大連接數時,不能再提供連接數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;}}
連接對象的代理類
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;/*** 連接對象的代理類*/ public class MyConnectionProxy implements Connection{private Connection realConn;private MyDataSource ds;//接收被代理類對象(JDBC4Connection)public MyConnectionProxy(Connection conn,MyDataSource ds){this.realConn = conn;this.ds = ds;}@Overridepublic void close() throws SQLException {//改寫:把連接放回連接池//調用連接池釋放連接的方法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";//設計一個集合用于存放連接對象private static LinkedList<Connection> pool = new LinkedList<Connection>();//初始化連接數private int initConn = 5;//數據庫能夠承受的最大連接數private int maxConn = 10;//用于記錄連接池一共提供了多少個連接數private int curConn = 0;//當初始化連接池程序的時候,就已經初始化了若干個對象public MyDataSource(){//創建5個連接對象,放入集合中for(int i =1 ; i <= initConn; i ++){curConn++;pool.add(createConnection());}}static{//注冊驅動try{Class.forName(driverClass);}catch(ClassNotFoundException e){e.printStackTrace();}}//創建一個連接對象的方法public Connection createConnection(){try{//被代理類對象Connection conn = DriverManager.getConnection(url,user,password);//創建代理類對象MyConnectionProxy proxy = new MyConnectionProxy(conn,this);return proxy; }catch(SQLException e){ e.printStackTrace();throw new RuntimeException();}}//這個方法提供給外部程序獲取連接對象的@Overridepublic Connection getConnection() throws SQLException {//情況1:并發連接數小于等于初始化連接數的時候,直接初始化連接取出即可if(pool.size()>0){Connection conn = pool.removeLast();return conn;}//情況2:并發連接數大于初始連接數且小于最大連接數,重新再創建新的鏈接給用戶if(curConn<maxConn){curConn++;return createConnection();}//情況3:并發連接數大于最大連接數時,不能再提供連接數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;}}
連接對象的代理類
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;/*** 連接對象的代理類*/ public class MyConnectionProxy implements Connection{private Connection realConn;private MyDataSource ds;//接收被代理類對象(JDBC4Connection)public MyConnectionProxy(Connection conn,MyDataSource ds){this.realConn = conn;this.ds = ds;}@Overridepublic void close() throws SQLException {//改寫:把連接放回連接池//調用連接池釋放連接的方法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;}}
總結
- 上一篇: JDBC进阶:调用数据库,将文件或其他字
- 下一篇: D3P0实践小例子