原生jdbc连接池

import java.io.InputStream;
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.util.LinkedList;
import java.util.Properties;

import javax.sql.DataSource;

/**
 * 原生jdbc连接池
 * 
 * @author guweiqiang
 */
public class JdbcPool implements DataSource{
	
	/**
	 * 使用LinkedList存放数据库连接池中的连接
	 */
	private static LinkedList<Connection> connList = new LinkedList<Connection>();
	
	/**
	 * 在静态代码块中加载db.properties数据库配置文件
	 */
	static {
		InputStream is = JdbcPool.class.getClassLoader().getResourceAsStream("mysql/db.properties");
		Properties prop = new Properties();
		
		try {
			// 获取配置文件参数
			prop.load(is);
			String driver = prop.getProperty("driver");
			String url = prop.getProperty("url");
			String user = prop.getProperty("user");
			String password = prop.getProperty("password");
			int initPoolSize = Integer.parseInt(prop.getProperty("initPoolSize"));
			
			//加载数据库驱动
            Class.forName(driver);
            
            // 初始化连接池
            Connection conn = null; // 连接对象
            for (int i = 0; i < initPoolSize; i++) {
            	conn = DriverManager.getConnection(url, user, password);
            	connList.add(conn);
            }
			
		} catch (Exception e){
			e.printStackTrace();
		}
		
	}
	

	@Override
	public PrintWriter getLogWriter() throws SQLException {
		return null;
	}

	@Override
	public void setLogWriter(PrintWriter out) throws SQLException {
		
	}

	@Override
	public void setLoginTimeout(int seconds) throws SQLException {
		
	}

	@Override
	public int getLoginTimeout() throws SQLException {
		return 0;
	}

	@Override
	public <T> T unwrap(Class<T> iface) throws SQLException {
		return null;
	}

	@Override
	public boolean isWrapperFor(Class<?> iface) throws SQLException {
		return false;
	}

	/**
	 * 获取数据库连接
	 */
	@Override
	public Connection getConnection() throws SQLException {
		// 如果数据库连接池中的连接对象数>0
		if(connList.size()>0){
			// 从数据库连接池中pop出一个连接对象
			final Connection conn = connList.removeFirst();
			System.out.println("连接池剩余连接数:" + connList.size());
			
			// 返回Connection对象
			return (Connection)Proxy.newProxyInstance(JdbcPool.class.getClassLoader(), conn.getClass().getInterfaces(), new InvocationHandler(){

				@Override
				public Object invoke(Object proxy, Method method, Object[] args)
						throws Throwable {
					if(!"close".equals(method.getName())){ // 非close方法,正常调用
						return method.invoke(conn, args);
					} else { // close方法,释放连接
						connList.add(conn); // 放还到连接池中
						System.out.println(conn + "被还给数据库连接池了!!");
						System.out.println("放还后连接池连接数:" + connList.size());
						return null;
					}
				}
			});
			
		} else {
			throw new RuntimeException("对不起,数据库忙");
		}
	}

	@Override
	public Connection getConnection(String username, String password)
			throws SQLException {
		// TODO Auto-generated method stub
		return null;
	}

}

mysql/db.properties:

driver=com.mysql.jdbc.Driver
url=jdbc:mysql://172.19.59.48:3306,172.19.59.50:3306/mysql?autoReconnect=true
user=root
password=123456
initPoolSize=5

测试代码:

import java.sql.Connection;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;

public class TestJdbcPool {
	
	private static JdbcPool pool = new JdbcPool();

	public static void main(String[] args) {
		List<User> userList = new ArrayList<User>();
		Connection conn = null;
		Statement stmt = null;
		
		try {
			// 建立连接
			conn = pool.getConnection();
			
			String sql = "select * from student";
			stmt = conn.createStatement();
			ResultSet rs = stmt.executeQuery(sql);
			while (rs.next()) {
				User user = new User();
				user.setName(rs.getString("name"));
				user.setAge(rs.getInt("age"));
				userList.add(user);
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			if(conn != null){
				try {
					conn.close();
				} catch (SQLException e) {
					e.printStackTrace();
				}
			}
		}

		for(User user : userList){
			System.out.println("name:" + user.getName() + "\t age:" + user.getAge());
		}
	}

}

猜你喜欢

转载自guwq2014.iteye.com/blog/2393091