Native jdbc connection pool

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;

/**
 * Native jdbc connection pool
 *
 * @author guweiqiang
 */
public class JdbcPool implements DataSource{
	
	/**
	 * Use LinkedList to store connections in the database connection pool
	 */
	private static LinkedList<Connection> connList = new LinkedList<Connection>();
	
	/**
	 * Load the db.properties database configuration file in the static code block
	 */
	static {
		InputStream is = JdbcPool.class.getClassLoader().getResourceAsStream("mysql/db.properties");
		Properties prop = new Properties();
		
		try {
			// Get configuration file parameters
			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"));
			
			//load database driver
            Class.forName(driver);
            
            // initialize the connection pool
            Connection conn = null; // connection object
            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;
	}

	/**
	 * Get database connection
	 */
	@Override
	public Connection getConnection() throws SQLException {
		// If the number of connection objects in the database connection pool is > 0
		if(connList.size()>0){
			// pop a connection object from the database connection pool
			final Connection conn = connList.removeFirst();
			System.out.println("Number of remaining connections in the connection pool: " + connList.size());
			
			// return the Connection object
			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())){ // non-close method, call normally
						return method.invoke(conn, args);
					} else { // close method, release the connection
						connList.add(conn); // put back into the connection pool
						System.out.println(conn + "Returned to the database connection pool!!");
						System.out.println("Number of connection pool connections after releasing: " + connList.size());
						return null;
					}
				}
			});
			
		} else {
			throw new RuntimeException("Sorry, the database is busy");
		}
	}

	@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

 

Test code:

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 {
			// establish connection
			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());
		}
	}

}

 

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=326222266&siteId=291194637