黑马程序员 JDBC_通过代理模式来保持用户关闭连接的习惯,代理设计模式(李勇老师)
2014-01-03 14:34
267 查看
很多框架都是采用这种代理的这种形式,但是以下代码可能不严谨,对于学习框架还是很有用的。
数据源包下的mycollection:
数据源代码:真正开发时,是不需要自己写的。
连接数据库的工具类:调用的依然是关闭的方法close,但是被拦截下来啦,执行的结果不一样,不是关闭数据库的连接
测试代码:
public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
Connection conn = JdbcUtils.getConnection();
System.out.println(conn);
JdbcUtils.free(null, null, conn);
}
}
自己建立一个connection,实现connection接口,覆盖close方法,一调用close方法,不是关闭连接而是把连接加入到连接池,让别的开发人员使用起来和调用以前的close方法一样
结果:
cn.itcast.jdbc.datasource.MyConnection@def14f
cn.itcast.jdbc.datasource.MyConnection@def14f
cn.itcast.jdbc.datasource.MyConnection@def14f
cn.itcast.jdbc.datasource.MyConnection@def14f
cn.itcast.jdbc.datasource.MyConnection@def14f
cn.itcast.jdbc.datasource.MyConnection@836727
cn.itcast.jdbc.datasource.MyConnection@836727
cn.itcast.jdbc.datasource.MyConnection@836727
cn.itcast.jdbc.datasource.MyConnection@836727
cn.itcast.jdbc.datasource.MyConnection@836727
数据源包下的mycollection:
public class MyConnection implements Connection { private Connection realConnection; private MyDataSource2 dataSource; private int maxUseCount = 5; private int currentUserCount = 0; MyConnection(Connection connection, MyDataSource2 dataSource) { this.realConnection = connection; this.dataSource = dataSource; } public void clearWarnings() throws SQLException { this.realConnection.clearWarnings(); } public void close() throws SQLException { this.currentUserCount++; if (this.currentUserCount < this.maxUseCount) this.dataSource.connectionsPool.addLast(this); else { this.realConnection.close(); this.dataSource.currentCount--; } } public void commit() throws SQLException { this.realConnection.commit(); } public Statement createStatement() throws SQLException { return this.realConnection.createStatement(); } public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { // TODO Auto-generated method stub return null; } public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { // TODO Auto-generated method stub return null; } public boolean getAutoCommit() throws SQLException { // TODO Auto-generated method stub return false; } public String getCatalog() throws SQLException { // TODO Auto-generated method stub return null; } public int getHoldability() throws SQLException { // TODO Auto-generated method stub return 0; } public DatabaseMetaData getMetaData() throws SQLException { // TODO Auto-generated method stub return null; } public int getTransactionIsolation() throws SQLException { // TODO Auto-generated method stub return 0; } public Map<String, Class<?>> getTypeMap() throws SQLException { // TODO Auto-generated method stub return null; } public SQLWarning getWarnings() throws SQLException { // TODO Auto-generated method stub return null; } public boolean isClosed() throws SQLException { // TODO Auto-generated method stub return false; } public boolean isReadOnly() throws SQLException { // TODO Auto-generated method stub return false; } public String nativeSQL(String sql) throws SQLException { // TODO Auto-generated method stub return null; } public CallableStatement prepareCall(String sql) throws SQLException { // TODO Auto-generated method stub return null; } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { // TODO Auto-generated method stub return null; } public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { // TODO Auto-generated method stub return null; } public PreparedStatement prepareStatement(String sql) throws SQLException { // TODO Auto-generated method stub return null; } public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { // TODO Auto-generated method stub return null; } public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { // TODO Auto-generated method stub return null; } public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { // TODO Auto-generated method stub return null; } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { // TODO Auto-generated method stub return null; } public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { // TODO Auto-generated method stub return null; } public void releaseSavepoint(Savepoint savepoint) throws SQLException { // TODO Auto-generated method stub } public void rollback() throws SQLException { // TODO Auto-generated method stub } public void rollback(Savepoint savepoint) throws SQLException { // TODO Auto-generated method stub } public void setAutoCommit(boolean autoCommit) throws SQLException { // TODO Auto-generated method stub } public void setCatalog(String catalog) throws SQLException { // TODO Auto-generated method stub } public void setHoldability(int holdability) throws SQLException { // TODO Auto-generated method stub } public void setReadOnly(boolean readOnly) throws SQLException { // TODO Auto-generated method stub } public Savepoint setSavepoint() throws SQLException { // TODO Auto-generated method stub return null; } public Savepoint setSavepoint(String name) throws SQLException { // TODO Auto-generated method stub return null; } public void setTransactionIsolation(int level) throws SQLException { // TODO Auto-generated method stub } public void setTypeMap(Map<String, Class<?>> map) throws SQLException { // TODO Auto-generated method stub } @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 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; } }
数据源代码:真正开发时,是不需要自己写的。
public class MyDataSource2 implements DataSource { private static String url = "jdbc:mysql://localhost:3306/jdbc"; private static String user = "root"; private static String password = "root"; private static int initCount = 1; private static int maxCount = 1; int currentCount = 0; LinkedList<Connection> connectionsPool = new LinkedList<Connection>();// 针对接口编程,connection是接口 public MyDataSource2() { try { for (int i = 0; i < initCount; i++) { 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(); if (this.currentCount < maxCount) { this.currentCount++; return this.createConnection(); } 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; } public Connection getConnection(String username, String password) throws SQLException { // TODO Auto-generated method stub return null; } public PrintWriter getLogWriter() throws SQLException { // TODO Auto-generated method stub return null; } public int getLoginTimeout() throws SQLException { // TODO Auto-generated method stub return 0; } public void setLogWriter(PrintWriter out) throws SQLException { // TODO Auto-generated method stub } public void setLoginTimeout(int seconds) throws SQLException { // TODO Auto-generated method stub } @Override public Logger getParentLogger() throws SQLFeatureNotSupportedException { // TODO Auto-generated method stub return null; } @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; } }
连接数据库的工具类:调用的依然是关闭的方法close,但是被拦截下来啦,执行的结果不一样,不是关闭数据库的连接
public final class JdbcUtils { private static MyDataSource2 myDataSource = null; private JdbcUtils() { } static { try { Class.forName("com.mysql.jdbc.Driver"); myDataSource = new MyDataSource2(); } catch (Exception e) { throw new ExceptionInInitializerError(e); } } public static DataSource getDataSource() { return myDataSource; } public static Connection getConnection() throws SQLException { // return DriverManager.getConnection(url, user, password); 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(); } } } } }
测试代码:
public static void main(String[] args) throws Exception {
for (int i = 0; i < 10; i++) {
Connection conn = JdbcUtils.getConnection();
System.out.println(conn);
JdbcUtils.free(null, null, conn);
}
}
自己建立一个connection,实现connection接口,覆盖close方法,一调用close方法,不是关闭连接而是把连接加入到连接池,让别的开发人员使用起来和调用以前的close方法一样
结果:
cn.itcast.jdbc.datasource.MyConnection@def14f
cn.itcast.jdbc.datasource.MyConnection@def14f
cn.itcast.jdbc.datasource.MyConnection@def14f
cn.itcast.jdbc.datasource.MyConnection@def14f
cn.itcast.jdbc.datasource.MyConnection@def14f
cn.itcast.jdbc.datasource.MyConnection@836727
cn.itcast.jdbc.datasource.MyConnection@836727
cn.itcast.jdbc.datasource.MyConnection@836727
cn.itcast.jdbc.datasource.MyConnection@836727
cn.itcast.jdbc.datasource.MyConnection@836727
相关文章推荐
- JDBC学习笔记(18):通过代理模式来保持用户关闭连接的习惯
- 用代理模式 保持用户关闭链接的习惯
- 黑马程序员 JDBC_使用模板方法设计模式处理DAO中的方法(李勇老师)
- [JDBC]数据库连接池拦截close的方法/代理模式关闭连接
- 黑马程序员 JDBC_编写一个基本的连接池来实现连接的复用,优化工作(李勇老师)
- 通过java枚举实现的单例jdbc连接与关闭
- 黑马程序员_代理设计模式
- JDBC(2)JAVA连接数据库之 分页操作、事务操作、代理模式
- 黑马程序员——protocol的基本使用和代理设计模式
- JDBC 通过Wrapper接口释放连接资源(关闭连接的新方法)
- 黑马程序员 JDBC_如何使用开源项目DBCP(实际项目中常用)(李勇老师)
- 黑马程序员------[Objective-C]协议-代理设计模式
- 【转载】Java通过JDBC分别采用Windows身份验证模式和混合验证模式连接登录SQL Server2008数据库代码
- 黑马程序员--设计模式之代理模式 02
- DAO设计模式 -- 使用数据库连接类连接MySql数据库并实现添加用户
- 黑马程序员——OC基础学习(五)---分类(Category),代码块Block和protocol代理设计模式
- 由JDBC数据库连接所联想到的5种设计模式(转)
- java通过代理使用redis,redis自动关闭连接,释放资源
- 转:由JDBC数据库连接所联想到的五种设计模式
- oracle的sys用户怎么通过jdbc连接