手搓一个数据库连接池

手搓一个数据库连接池

继承DataSource接口

/**
 * @author fate
 * @date 2022/11/3
 * @Description
 */
public interface FateDataSourceInterface extends DataSource {
    /**
     * 获得连接(必须实现)
     *
     * @return {@link Connection}
     * @throws SQLException sqlexception异常
     */
    @Override
    default Connection getConnection() throws SQLException{
        return null;
    }

    /**
     * 获得连接(必须实现)
     *
     * @param username 用户名
     * @param password 密码
     * @return {@link Connection}
     * @throws SQLException sqlexception异常
     */
    @Override
    default Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

    /**
     * 打开
     *
     * @param iface iface
     * @return {@link T}
     * @throws SQLException sqlexception异常
     */
    @Override
    default <T> T unwrap(Class<T> iface) throws SQLException {
        return null;
    }

    /**
     * 是包装
     *
     * @param iface iface
     * @return boolean
     * @throws SQLException sqlexception异常
     */
    @Override
    default boolean isWrapperFor(Class<?> iface) throws SQLException {
        return false;
    }

    /**
     * 获取日志
     *
     * @return {@link PrintWriter}
     * @throws SQLException sqlexception异常
     */
    @Override
    default PrintWriter getLogWriter() throws SQLException {
        return null;
    }

    /**
     * 设置日志
     *
     * @param out 出
     * @throws SQLException sqlexception异常
     */
    @Override
    default void setLogWriter(PrintWriter out) throws SQLException {

    }

    /**
     * 设置登录超时
     *
     * @param seconds 秒
     * @throws SQLException sqlexception异常
     */
    @Override
    default void setLoginTimeout(int seconds) throws SQLException {
    }

    /**
     * 获得登录超时
     *
     * @return int
     * @throws SQLException sqlexception异常
     */
    @Override
    default int getLoginTimeout() throws SQLException {
        return  0;
    }

    /**
     * 得到父母记录器
     *
     * @return {@link Logger}
     * @throws SQLFeatureNotSupportedException sqlfeature不支持例外
     */
    @Override
    default Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}

编写一个抽象类注入数据库连接信息

public abstract class AbstractFateDataSource implements FateDataSourceInterface {

//    数据库基本信息

    private String url;

    private String username;

    private String password;

    private String driver;




    public String getUsername() {
        return username;
    }

    public void setUsername(String username) {
        this.username = username;
    }

    public String getPassword() {
        return password;
    }

    public void setPassword(String password) {
        this.password = password;
    }

    public String getDriver() {
        return driver;
    }

    public void setDriver(String driver) {
        this.driver = driver;
    }

    public String getUrl() {
        return url;
    }

    public void setUrl(String url) {
        this.url = url;
    }

    /**
     * 获得连接(必须实现)
     *
     * @return {@link Connection}
     * @throws SQLException sqlexception异常
     */
    @Override
    public Connection getConnection() throws SQLException {
        return getConnection(username, password);
    }

    /**
     * 获得连接(必须实现)
     *
     * @param username 用户名
     * @param password 密码
     * @return {@link Connection}
     * @throws SQLException sqlexception异常
     */
    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return doConnect(username, password);
    }

    /**
     * 获取连接
     *
     * @param username 用户名
     * @param password 密码
     * @return {@link Connection}
     */
    private Connection doConnect(String username, String password) throws SQLException {
        return DriverManager.getConnection(url, username, password);
    }
}

采用动态代理实现对数据库连接的代理

public class ConnectionProxy implements InvocationHandler {

    /**
     * 真正连接
     */
    private Connection realConnection;

    /**
     * 代理连接
     */
    private Connection proxyConnection;

    /**
     * 数据源
     */
    private FateDataSource dataSource;


    public ConnectionProxy(Connection realConnection, FateDataSource dataSource) {
        this.realConnection = realConnection;
        this.dataSource = dataSource;
        this.proxyConnection = (Connection) Proxy.newProxyInstance(Connection.class.getClassLoader(),new Class<?>[]{Connection.class},this);
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
//        获取方法名字
        String methodName = method.getName();
        if ("close".equals(methodName)){
//           链接归还连接池
            dataSource.closeConnection(this);
            return null;
        }else {
            return method.invoke(realConnection, args);
        }

    }

    public Connection getRealConnection() {
        return realConnection;
    }

    public void setRealConnection(Connection realConnection) {
        this.realConnection = realConnection;
    }

    public Connection getProxyConnection() {
        return proxyConnection;
    }

    public void setProxyConnection(Connection proxyConnection) {
        this.proxyConnection = proxyConnection;
    }

    public FateDataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(FateDataSource dataSource) {
        this.dataSource = dataSource;
    }

}

编写抽象类实现类

public class FateDataSource extends AbstractFateDataSource{
    /**
     * 空闲连接
     */
    private final List<ConnectionProxy> idleConnections = new ArrayList<>();
    /**
     * 活跃连接
     */
    private final List<ConnectionProxy> activeConnections = new ArrayList<>();
    /**
     * 最大活跃连接池
     */
    private  int poolMaxActiveConnections=10;
    /**
     * 最大空闲连接池
     */
    private  int poolMaxIdleConnections=5;
    /**
     * 连接池等待时间
     */
    private  long poolMaxToWait= 30000L;
    private final Object monitor = new Object();

    public FateDataSource() {
    }

    public FateDataSource(int poolMaxActiveConnections, int poolMaxIdleConnections, long poolMaxToWait) {
        this.poolMaxActiveConnections = poolMaxActiveConnections;
        this.poolMaxIdleConnections = poolMaxIdleConnections;
        this.poolMaxToWait = poolMaxToWait;
    }

    /**
     * 获得连接(必须实现)
     *
     * @return {@link Connection}
     */
    @Override
    public Connection getConnection() throws SQLException {
        ConnectionProxy connectionProxy = getConnectionProxy(super.getUsername(),super.getPassword());
        return connectionProxy.getProxyConnection();
    }

    private ConnectionProxy getConnectionProxy(String username, String password) throws SQLException {
        Boolean wait = false;
        ConnectionProxy connectionProxy=null;
        while (connectionProxy==null){
//            线程同步
            synchronized (monitor){
                if (!idleConnections.isEmpty()){
//                    空闲链接直接使用
                    connectionProxy=idleConnections.remove(0);
                }else {
//                    未达到最大链接数,直接新建链接
                    if (activeConnections.size()<poolMaxActiveConnections){
                        connectionProxy = new ConnectionProxy(super.getConnection(username, password), this);
                    }
//                        反之等待
                }
            }
            if (!wait){
                wait = true;
            }
            if (connectionProxy==null){
                try {
//                   空链接需要等待
                    monitor.wait(poolMaxToWait);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                    break;
                }
            }
        }
        if (connectionProxy!=null){
            activeConnections.add(connectionProxy);
        }
        return connectionProxy;
    }


    public void closeConnection(ConnectionProxy connectionProxy){
        synchronized (monitor){
//            逻辑关闭实则只是放在另外一个list中
            activeConnections.remove(connectionProxy);
            if (idleConnections.size()<poolMaxIdleConnections){
                idleConnections.add(connectionProxy);
            }
//            通知等待获取链接的线程
            monitor.notify();
        }
    }
}

你可能感兴趣的:(代码心得与一些很值得记录的错误,数据库,java,服务器)