自定义数据库连接池

 2023-09-07 阅读 23 评论 0

摘要:自定义数据库连接池 连接池主要还是为了重用连接,那么接下来简单的介绍一个自实现的连接池。 建立自定义数据源类并实现javax.sql.DataSource接口 因为只是简单的模拟一下,这里只实现getConnection方法。 package com.pc.jdbc.mydatasource;import java.io.Pri

自定义数据库连接池

连接池主要还是为了重用连接,那么接下来简单的介绍一个自实现的连接池。

  1. 建立自定义数据源类并实现javax.sql.DataSource接口

因为只是简单的模拟一下,这里只实现getConnection方法。
package com.pc.jdbc.mydatasource;import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.SQLException;
import java.sql.SQLFeatureNotSupportedException;
import java.util.LinkedList;
import java.util.logging.Logger;import javax.sql.DataSource;/*** 自定义连接池** @author Switch* @data 2016年9月30日* @version V1.0*/
public class MyDataSource implements DataSource {/*** 队列模拟线程池*/private static LinkedList<Connection> dataSource = null;/*** 初始化连接池*/static {dataSource = new LinkedList<>();for (int i = 0; i < 20; i++) {// 通过工具类获取原始连接对象Connection ct = JDBCUtils.getConnection();// 将连接对象进行装饰,实现close的方法的覆盖,归还到连接池MyConnection myCt = new MyConnection(ct, dataSource);dataSource.add(myCt);}}/*** 从线程池中获取连接*/@Overridepublic Connection getConnection() throws SQLException {// 该版本并未考虑多线程及空闲连接和激活连接// 所以说当连接不够时,只会再添加一些连接if (dataSource.isEmpty()) {for (int i = 0; i < 5; i++) {dataSource.add(new MyConnection(JDBCUtils.getConnection(), dataSource));}}return dataSource.removeFirst();}@Overridepublic PrintWriter getLogWriter() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic int getLoginTimeout() throws SQLException {// TODO Auto-generated method stubreturn 0;}@Overridepublic Logger getParentLogger() throws SQLFeatureNotSupportedException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setLogWriter(PrintWriter arg0) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setLoginTimeout(int arg0) throws SQLException {// TODO Auto-generated method stub}@Overridepublic boolean isWrapperFor(Class<?> arg0) throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic <T> T unwrap(Class<T> arg0) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Connection getConnection(String arg0, String arg1) throws SQLException {// TODO Auto-generated method stubreturn null;}}

  1. 将获取连接的操作抽出来,封装成工具类

package com.pc.jdbc.mydatasource;import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.util.Properties;/*** JDBC工具类* @author Switch* @data 2016年9月30日* @version V1.0*/
public class JDBCUtils {private static String driver = null;private static String url = null;private static String username = null;private static String password = null;static {InputStream is = null;try {Properties props = new Properties();is = JDBCUtils.class.getClassLoader().getResourceAsStream("db.properties");props.load(is);driver = props.getProperty("mysql.driver");url = props.getProperty("mysql.url");username = props.getProperty("mysql.username");password = props.getProperty("mysql.password");} catch (IOException e) {e.printStackTrace();throw new RuntimeException();} finally {if (is != null) {try {is.close();} catch (IOException e) {e.printStackTrace();throw new RuntimeException();}}}}/*** 获得连接** @return 连接*/public static Connection getConnection() {Connection ct = null;try {Class.forName(driver);ct = DriverManager.getConnection(url, username, password);} catch (Exception e) {e.printStackTrace();throw new RuntimeException();}return ct;}}

PS:db.properties文件如下:(放在类路径根目录下)
# mysql info
mysql.driver=com.mysql.jdbc.Driver
mysql.url=jdbc:mysql://localhost:3306/test?useUnicode=true&characterEncoding=utf8
mysql.username=root
mysql.password=123456

  1. 使用装饰者模式实现Connection的close()方法改为释放回连接池

package com.pc.jdbc.mydatasource;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.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;/*** 使用装饰者模式,简单的实现了连接关闭的复写,实现将关闭连接加入连接池** @author Switch* @data 2016年9月30日* @version V1.0*/
public class MyConnection implements Connection {// 1.持有Connection接口和连接池Connection ct = null;LinkedList<Connection> dataSource = null;/*** 通过传入的参数,初始化持有对象** @param ct*            连接* @param dataSource*            连接池*/public MyConnection(Connection ct, LinkedList<Connection> dataSource) {this.ct = ct;this.dataSource = dataSource;}/*** 将装饰后的连接重新加入到连接池中*/@Overridepublic void close() throws SQLException {this.dataSource.add(this);}// 之后的方法,要使用哪个,就实现哪个,如果功能没改变,则可以直接使用持有对象ct的相同调用@Overridepublic PreparedStatement prepareStatement(String arg0) throws SQLException {return this.ct.prepareStatement(arg0);}@Overridepublic boolean isWrapperFor(Class<?> arg0) throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic <T> T unwrap(Class<T> arg0) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void abort(Executor arg0) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void clearWarnings() throws SQLException {// TODO Auto-generated method stub}@Overridepublic void commit() throws SQLException {// TODO Auto-generated method stub}@Overridepublic Array createArrayOf(String arg0, Object[] arg1) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Blob createBlob() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Clob createClob() 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 Statement createStatement() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Statement createStatement(int arg0, int arg1) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Statement createStatement(int arg0, int arg1, int arg2) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Struct createStruct(String arg0, Object[] arg1) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic boolean getAutoCommit() throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic String getCatalog() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Properties getClientInfo() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic String getClientInfo(String arg0) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic int getHoldability() throws SQLException {// TODO Auto-generated method stubreturn 0;}@Overridepublic DatabaseMetaData getMetaData() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic int getNetworkTimeout() throws SQLException {// TODO Auto-generated method stubreturn 0;}@Overridepublic String getSchema() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic int getTransactionIsolation() throws SQLException {// TODO Auto-generated method stubreturn 0;}@Overridepublic Map<String, Class<?>> getTypeMap() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic SQLWarning getWarnings() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic boolean isClosed() throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic boolean isReadOnly() throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic boolean isValid(int arg0) throws SQLException {// TODO Auto-generated method stubreturn false;}@Overridepublic String nativeSQL(String arg0) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic CallableStatement prepareCall(String arg0) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic CallableStatement prepareCall(String arg0, int arg1, int arg2) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic CallableStatement prepareCall(String arg0, int arg1, int arg2, int arg3) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String arg0, int arg1) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String arg0, int[] arg1) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String arg0, String[] arg1) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String arg0, int arg1, int arg2) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic PreparedStatement prepareStatement(String arg0, int arg1, int arg2, int arg3) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void releaseSavepoint(Savepoint arg0) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void rollback() throws SQLException {// TODO Auto-generated method stub}@Overridepublic void rollback(Savepoint arg0) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setAutoCommit(boolean arg0) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setCatalog(String arg0) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setClientInfo(Properties arg0) throws SQLClientInfoException {// TODO Auto-generated method stub}@Overridepublic void setClientInfo(String arg0, String arg1) throws SQLClientInfoException {// TODO Auto-generated method stub}@Overridepublic void setHoldability(int arg0) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setNetworkTimeout(Executor arg0, int arg1) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setReadOnly(boolean arg0) throws SQLException {// TODO Auto-generated method stub}@Overridepublic Savepoint setSavepoint() throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic Savepoint setSavepoint(String arg0) throws SQLException {// TODO Auto-generated method stubreturn null;}@Overridepublic void setSchema(String arg0) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setTransactionIsolation(int arg0) throws SQLException {// TODO Auto-generated method stub}@Overridepublic void setTypeMap(Map<String, Class<?>> arg0) throws SQLException {// TODO Auto-generated method stub}}

方法增强

方法增强有4种方法,继承、装饰者、动态代理和字节码增强。
  1. 继承, 子类继承父类, 将父类的方法进行复写, 从而进行增强。使用前提: 必须有父类, 且存在继承关系。
  2. 装饰者设计模式, 此设计模式专门用于增强方法。使用前提: 必须有接口。缺点: 需要将接口的所有方法都实现。
  3. 动态代理: 在运行时动态的创建代理类, 完成增强操作。 与装饰者相似使用前提: 必须有接口。难点: 需要反射技术。
  4. 字节码增强, 运行时创建目标类子类, 从而进行增强。常见第三方框架:cglib、javassist等。

装饰者模式

装饰者固定结构: 接口A, 已知实现类C, 需要装饰者创建代理类B。

  1. 创建类B,并实现接口A 。
  2. 提供类B的构造方法,参数类型为A,用于接收A接口的其他实现类C的对象 。
  3. 给类B添加类型为A成员变量,用于存放A接口的其他实现类的对象。
  4. 增强需要的方法。
  5. 实现不需要增强的方法,方法体重新调用成员变量存放的其他实现类对应的方法。

  1. 测试自定义数据库连接池

package com.pc.jdbc.mydatasource;import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;import org.junit.Test;public class TestMyDataSource {@Testpublic void test() {MyDataSource dataSource = new MyDataSource();Connection ct = null;PreparedStatement pstmt = null;ResultSet rs = null;try {ct = dataSource.getConnection();String sql = "select * from users";pstmt = ct.prepareStatement(sql);rs = pstmt.executeQuery();while (rs.next()) {System.out.println(rs.getInt("id") + " " + rs.getString("username") + " " + rs.getString("password"));}} catch (SQLException e) {e.printStackTrace();} finally {try {if (rs != null) {rs.close();}if (pstmt != null) {pstmt.close();}if (ct != null) {ct.close();}} catch (SQLException e) {e.printStackTrace();}}}
}


PS:附上GitHub地址https://github.com/Switch-vov/the-example-datasource



版权声明:本站所有资料均为网友推荐收集整理而来,仅供学习和研究交流使用。

原文链接:https://hbdhgg.com/4/14881.html

发表评论:

本站为非赢利网站,部分文章来源或改编自互联网及其他公众平台,主要目的在于分享信息,版权归原作者所有,内容仅供读者参考,如有侵权请联系我们删除!

Copyright © 2022 匯編語言學習筆記 Inc. 保留所有权利。

底部版权信息