首页 > 编程语言 > 详细

java自定义连接池

时间:2019-01-13 12:58:19      阅读:38      评论:0      收藏:0      [点我收藏+]

标签:exception   ade   rac   spa   char   rem   etc   evel   column   

1、java自定义连接池

  1.1连接池的概念:

   实际开发中"获取连接"或“释放资源”是非常消耗系统资源的两个过程,为了姐姐此类性能问题,通常情况我们采用连接池技术来贡献连接Connection

   用池来管理Connection,这样可以重复使用Connection,有了池,所以我们就不用自己来创建Connection,而是通过池来获取Connection对象,当使用完Connection后,调用Connection的close()方法也不会真的关闭Connection,而是把Connection“归还”给池,池也就可以再利用这个Connection对象啦

  1.2 自定义连接池需要如下步骤

    1.2.1 创建连接池实现(数据源),并实现接口javax.sql.DataSource.简化本案案例,我们可以自己提供方法,没有实现接口

    1.2.2 提供一个集合,用于存放连接,因为移除/添加操作过多,所以选用LinkedList较好

    1.2.3 为连接池初始化5个连接

    1.2.4 程序如果需要连接,调用实现类的getConnection(),本方法姜葱连接池(容器List)获取连接,为了保证当前连接只是停工给一个线程使用,我们需要将连接先从连接池冲移除。

    1.2.5 当用户使用完连接,释放资源时,不执行close()方法,而是将连接添加到连接池中

  代码实现:

 

package com.rookie.bigdata.utils;

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.Properties;

/**
 * @author
 * @date 2019/1/13
 */
public class JDBCUtils {

    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    /**
     * 静态代码块加载配置文件信息
     */
    static {
        try {
            // 1.通过当前类获取类加载器
            ClassLoader classLoader = JDBCUtils.class.getClassLoader();
            // 2.通过类加载器的方法获得一个输入流
            InputStream is = classLoader.getResourceAsStream("db.properties");
            // 3.创建一个properties对象
            Properties props = new Properties();
            // 4.加载输入流
            props.load(is);
            // 5.获取相关参数的值
            driver = props.getProperty("driver");
            url = props.getProperty("url");
            username = props.getProperty("username");
            password = props.getProperty("password");
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取连接方法
     *
     * @return
     */
    public static Connection getConnection() {
        Connection conn = null;
        try {
            Class.forName(driver);
            conn = DriverManager.getConnection(url, username, password);
        } catch (Exception e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 释放资源方法
     *
     * @param conn
     * @param pstmt
     * @param rs
     */
    public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (pstmt != null) {
            try {
                pstmt.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
        if (conn != null) {
            try {
                conn.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

    }
}
package com.rookie.bigdata.datasource;

import com.rookie.bigdata.utils.JDBCUtils;

import javax.sql.DataSource;
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;

/**
 * @author liuxili
 * @date 2019/1/13
 */
public class MyDataSource implements DataSource {

    //创建一个容器,用于存放connection对象
    private static LinkedList<Connection> pool = new LinkedList<>();

    //初始化5个连接,放到容器中
    static {
        for (int i = 0; i < 5; i++) {
            Connection connection = JDBCUtils.getConnection();
            pool.add(connection);
        }
    }

    /**
     * 获取连接的方法
     *
     * @return
     * @throws SQLException
     */
    @Override
    public Connection getConnection() throws SQLException {

        //当连接池中没有连接的时候,需要创建链接
        if (pool.size() == 0) {
            for (int i = 0; i < 5; i++) {
                Connection connection = JDBCUtils.getConnection();
                pool.add(connection);
            }
        }

        //从池中获取连接
        return pool.remove(0);
    }


    /**
     * 归还连接到连接池中
     *
     * @param connection
     */
    public void releaseConnetion(Connection connection) {
        pool.add(connection);

    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

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

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

    @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 Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}
driver=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/web?useUnicode=true&characterEncoding=utf8
username=root
password=root

  测试类:

  

package com.rookie.bigdata.datasource;

import org.junit.Test;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.SQLException;

import static org.junit.Assert.*;

/**
 * @author
 * @date 2019/1/13
 */
public class MyDataSourceTest {

    @Test
    public void test1() throws SQLException {
        MyDataSource myDataSource = new MyDataSource();
        Connection connection = myDataSource.getConnection();
        String sql = "insert into H_USER values(?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,1);
        preparedStatement.setString(2, "张三");
        preparedStatement.setInt(3, 23);

        int rows = preparedStatement.executeUpdate();
        System.out.println(rows);

        myDataSource.releaseConnetion(connection);


    }


}

 

java自定义连接池改进

   实现Connection接口

  

package com.rookie.bigdata.datasource;

import java.sql.*;
import java.util.LinkedList;
import java.util.Map;
import java.util.Properties;
import java.util.concurrent.Executor;

/**
 * @author
 * @date 2019/1/13
 */
//实现一个Connection接口
public class MyConnection implements Connection {
    //定义一个变量
    private Connection connection;

    private LinkedList<Connection> pool;

    //编写构造方法
    public MyConnection(Connection connection, LinkedList<Connection> pool){

        this.connection=connection;
        this.pool=pool;
    }

    @Override
    public void close() throws SQLException {
        pool.add(connection);

    }
    @Override
    public PreparedStatement prepareStatement(String sql) throws SQLException {
        return connection.prepareStatement(sql);
    }

    @Override
    public Statement createStatement() throws SQLException {
        return null;
    }



    @Override
    public CallableStatement prepareCall(String sql) throws SQLException {
        return null;
    }

    @Override
    public String nativeSQL(String sql) throws SQLException {
        return null;
    }

    @Override
    public void setAutoCommit(boolean autoCommit) throws SQLException {

    }

    @Override
    public boolean getAutoCommit() throws SQLException {
        return false;
    }

    @Override
    public void commit() throws SQLException {

    }

    @Override
    public void rollback() throws SQLException {

    }


    @Override
    public boolean isClosed() throws SQLException {
        return false;
    }

    @Override
    public DatabaseMetaData getMetaData() throws SQLException {
        return null;
    }

    @Override
    public void setReadOnly(boolean readOnly) throws SQLException {

    }

    @Override
    public boolean isReadOnly() throws SQLException {
        return false;
    }

    @Override
    public void setCatalog(String catalog) throws SQLException {

    }

    @Override
    public String getCatalog() throws SQLException {
        return null;
    }

    @Override
    public void setTransactionIsolation(int level) throws SQLException {

    }

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

    @Override
    public SQLWarning getWarnings() throws SQLException {
        return null;
    }

    @Override
    public void clearWarnings() throws SQLException {

    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return null;
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
        return null;
    }

    @Override
    public Map<String, Class<?>> getTypeMap() throws SQLException {
        return null;
    }

    @Override
    public void setTypeMap(Map<String, Class<?>> map) throws SQLException {

    }

    @Override
    public void setHoldability(int holdability) throws SQLException {

    }

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

    @Override
    public Savepoint setSavepoint() throws SQLException {
        return null;
    }

    @Override
    public Savepoint setSavepoint(String name) throws SQLException {
        return null;
    }

    @Override
    public void rollback(Savepoint savepoint) throws SQLException {

    }

    @Override
    public void releaseSavepoint(Savepoint savepoint) throws SQLException {

    }

    @Override
    public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return null;
    }

    @Override
    public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
        return null;
    }

    @Override
    public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
        return null;
    }

    @Override
    public Clob createClob() throws SQLException {
        return null;
    }

    @Override
    public Blob createBlob() throws SQLException {
        return null;
    }

    @Override
    public NClob createNClob() throws SQLException {
        return null;
    }

    @Override
    public SQLXML createSQLXML() throws SQLException {
        return null;
    }

    @Override
    public boolean isValid(int timeout) throws SQLException {
        return false;
    }

    @Override
    public void setClientInfo(String name, String value) throws SQLClientInfoException {

    }

    @Override
    public void setClientInfo(Properties properties) throws SQLClientInfoException {

    }

    @Override
    public String getClientInfo(String name) throws SQLException {
        return null;
    }

    @Override
    public Properties getClientInfo() throws SQLException {
        return null;
    }

    @Override
    public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
        return null;
    }

    @Override
    public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
        return null;
    }

    @Override
    public void setSchema(String schema) throws SQLException {

    }

    @Override
    public String getSchema() throws SQLException {
        return null;
    }

    @Override
    public void abort(Executor executor) throws SQLException {

    }

    @Override
    public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {

    }

    @Override
    public int getNetworkTimeout() 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;
    }
}

  

package com.rookie.bigdata.datasource;

import com.rookie.bigdata.utils.JDBCUtils;

import javax.sql.DataSource;
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;

/**
 * @author liuxili
 * @date 2019/1/13
 */
public class MyDataSource1 implements DataSource {

    //创建一个容器,用于存放connection对象
    private static LinkedList<Connection> pool = new LinkedList<>();

    //初始化5个连接,放到容器中
    static {
        for (int i = 0; i < 5; i++) {
            Connection connection = JDBCUtils.getConnection();
            MyConnection myConnection= new MyConnection(connection,pool);
            pool.add(myConnection);
        }
    }

    /**
     * 获取连接的方法
     *
     * @return
     * @throws SQLException
     */
    @Override
    public Connection getConnection() throws SQLException {
        Connection connection=null;
        //当连接池中没有连接的时候,需要创建链接
        if (pool.size() == 0) {
            for (int i = 0; i < 5; i++) {
                 connection = JDBCUtils.getConnection();
                MyConnection myConnection= new MyConnection(connection,pool);
                pool.add(myConnection);
            }
        }

        //从池中获取连接
        return pool.remove(0);
    }


//    /**
//     * 归还连接到连接池中
//     *
//     * @param connection
//     */
//    public void releaseConnetion(Connection connection) {
//        pool.add(connection);
//
//    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        return null;
    }

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

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

    @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 Logger getParentLogger() throws SQLFeatureNotSupportedException {
        return null;
    }
}

  测试代码

    @Test
    public void test2() throws SQLException {



        MyDataSource1 myDataSource = new MyDataSource1();
        Connection connection = myDataSource.getConnection();
        String sql = "insert into H_USER values(?,?,?)";
        PreparedStatement preparedStatement = connection.prepareStatement(sql);
        preparedStatement.setInt(1,2);
        preparedStatement.setString(2, "张三");
        preparedStatement.setInt(3, 23);

        int rows = preparedStatement.executeUpdate();
        System.out.println(rows);
        JDBCUtils.release(connection,preparedStatement,null);


    }

 

  至此自定义连接池实现完毕,参考黑马程序员视频教程

 

 

java自定义连接池

标签:exception   ade   rac   spa   char   rem   etc   evel   column   

原文:https://www.cnblogs.com/haizhilangzi/p/10262158.html

(0)
(0)
   
举报
评论 一句话评论(0
0条  
登录后才能评论!
© 2014 bubuko.com 版权所有 鲁ICP备09046678号-4
打开技术之扣,分享程序人生!
             

鲁公网安备 37021202000002号