模拟实现数据源

来源:互联网 发布:nginx lua redis 编辑:程序博客网 时间:2024/05/16 06:52
package com.jjyy.jdbc.pool;import java.io.FileReader;import java.io.PrintWriter;import java.lang.reflect.InvocationHandler;import java.lang.reflect.Method;import java.lang.reflect.Proxy;import java.sql.Connection;import java.sql.DriverManager;import java.sql.SQLException;import java.sql.SQLFeatureNotSupportedException;import java.util.LinkedList;import java.util.List;import java.util.Properties;import java.util.logging.Logger;import javax.sql.DataSource;/** * 自己写连接池 *  * @author JiangYu 2015年3月29日 * */public class MyDataSource implements DataSource {private static Integer min;private static Integer max;private static List<Connection> pool = new LinkedList<Connection>();private static Properties prop = null;static {try {prop = new Properties();prop.load(new FileReader(MyDataSource.class.getClassLoader().getResource("config.properties").getPath()));Class.forName(prop.getProperty("Driver"));for (int i = 0; i < min; i++) {Connection conn = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("userName"),prop.getProperty("passWord"));pool.add(conn);}} catch (Exception e) {e.printStackTrace();throw new RuntimeException(e);}}@Overridepublic Connection getConnection() throws SQLException {if (pool.size() == 0) {for (int i = 0; i < max - min; i++) {Connection conn = DriverManager.getConnection(prop.getProperty("url"), prop.getProperty("userName"),prop.getProperty("passWord"));pool.add(conn);}}final Connection conn = pool.remove(0);// 利用动态代理Connection proxy = (Connection) Proxy.newProxyInstance(conn.getClass().getClassLoader(), conn.getClass().getInterfaces(),new InvocationHandler() {@Overridepublic Object invoke(Object proxy, Method method,Object[] args) throws Throwable {if ("close".equals(method.getName())) {returnConn(conn);return null;} else {return method.invoke(conn, args);}}});return proxy;}private void returnConn(Connection conn) {try {if (conn != null && !conn.isClosed()) {pool.add(conn);}} catch (SQLException e) {e.printStackTrace();}}@Overridepublic Connection getConnection(String username, String password)throws SQLException {return null;}@Overridepublic PrintWriter getLogWriter() throws SQLException {return null;}@Overridepublic int getLoginTimeout() throws SQLException {return 0;}@Overridepublic Logger getParentLogger() throws SQLFeatureNotSupportedException {return null;}@Overridepublic void setLogWriter(PrintWriter arg0) throws SQLException {}@Overridepublic void setLoginTimeout(int arg0) throws SQLException {}@Overridepublic boolean isWrapperFor(Class<?> arg0) throws SQLException {return false;}@Overridepublic <T> T unwrap(Class<T> arg0) throws SQLException {return null;}public Integer getMin() {return min;}public void setMin(Integer min) {this.min = min;}public Integer getMax() {return max;}public void setMax(Integer max) {this.max = max;}}

0 0