数据库连接池

1、数据库辅助类

import java.io.FileInputStream;
import java.io.IOException;
import java.sql.*;
import java.util.Properties;

/**
 * Created by dwh on 2020/2/29.
 */
public class MyDBUtil {
    /**
     * 获取数据库连接对象
     *
     * @param driver   driver
     * @param url      url
     * @param user     user
     * @param password pwd
     * @return 数据库连接对象
     */
    public static Connection getConn(String driver, String url, String user, String password) {


        Connection conn = null;
        try {
            Class.forName(driver); //classLoader,加载对应驱动
            conn = DriverManager.getConnection(url, user, password);
        } catch (final ClassNotFoundException e) {
            e.printStackTrace();
        } catch (final SQLException e) {
            e.printStackTrace();
        }
        return conn;
    }

    /**
     * 关闭连接
     *
     * @param conn 数据库连接对象
     * @param pst  查询语句对象
     * @param rs   结果集对象
     */
    public static void close(Connection conn, PreparedStatement pst, ResultSet rs) {
        if (rs != null) {
            try {
                rs.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (pst != null) {
            try {
                pst.close();
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }

        if (null != conn) {
            try {
                conn.close();
            } catch (final SQLException e) {
                e.printStackTrace();
            }
        }
    }


    /**
     * 获取属性对象
     *
     * @param filePath 属性文件路径
     * @return 返回属性对象
     * @throws IOException ex
     */
    private static Properties getProp(String filePath) throws IOException {
        Properties prop;
        prop = new Properties();
        prop.load(new FileInputStream(filePath));
        return prop;
    }

    public static void main(String[] args) throws IOException {
        Properties prop = getProp("C:\\Users\\admin\\IdeaProjects\\statistics\\src\\main\\resources\\db.properties");
        Connection conn = null;
        PreparedStatement pst = null;
        ResultSet rs = null;

        try {
            conn = getConn(prop.getProperty("driver"), prop.getProperty("url"), prop.getProperty("user"), prop.getProperty("pwd"));
            pst = conn.prepareStatement("select * from test where id >= ?");
            pst.setInt(1, 2);
            rs = pst.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getString(1) + "\t" + rs.getString(2));  // rs的下标是从1开始
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            DBUtil.close(conn, pst, rs);
        }
    }
}

以上连接方式有个问题:用户每次请求都要获取数据库连接,而数据库创建连接的创建是非常消耗资源的。如果访问量过多,创建的连接数也会递增,极易造成数据库服务器的内存溢出,宕机!

2、数据库连接池

  • 数据库连接池技术核心思想是:连接复用。即创建这么一个池子(或叫容器,例如"数组"或"集合"),里面存一些已经创建好的数据库连接对象,并将其标志为"空闲"状态,用的时候从里面取一个来用,用完的时候再放回到池子里,随用随取,无需再创建再销毁!
  • 数据库连接池负责分配、管理和释放数据库连接,它允应用程序重复使用一个现有的数据库连接,而不是再重新建立一个;释放空闲时间超过最大空闲时间的数据库连接来避免因为没有释放数据库连接而引起的库连接遗漏。这项技术能明显提高数据库操作的性能。
  • 连接池自己应该具有自动初始化功能,自动增长功能,自动缩减功能。
  1. 自动增长:当池中的所有连接都被使用了,自动创建新的连接对象放入池中。
  2. 自动缩减:当池中空闲连接较多时,自动关闭部分连接。

3、自定义数据库连接池
java 提供了一套标准(一个接口),即数据库连接池应该有哪些功能(抽象方法), 如果我们能实现这个类,那么我们就可以自己定义一个数据库连接池了。

public class MyPool implements DataSource{
  // 实现一系列的方法,以下是最重要的一个方法
  public Connection getConnection() throws SQLException {
        return null;
    }

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

自己提供的数据库连接池,功能单一,健壮性也差。所以已经有很多厂商提供了数据库连接池的实现:

常见数据库连接池的实现.png

4、使用人家已经实现好的数据库连接池(以阿里的Druid为例)
可以参考github地址

  1. 首先pmo.xml导入工具jar包:
<!-- https://mvnrepository.com/artifact/com.alibaba/druid -->
<dependency>
    <groupId>com.alibaba</groupId>
    <artifactId>druid</artifactId>
    <version>1.1.10</version>
</dependency>
  1. 使用jar包
import com.alibaba.druid.pool.DruidDataSource;

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

/**
 * Created by dwh on 2020/2/29.
 */
public class DBPoolTest {
    public static void main(String[] args) throws IOException {
        // 1、创建工具类的入口对象
        DruidDataSource druidDataSource = new DruidDataSource();

        // 2、设置基本参数, 这些参数可以放在properties文件中
        Properties prop = getProp("C:\\Users\\admin\\IdeaProjects\\statistics\\src\\main\\resources\\db.properties");
        druidDataSource.setDriverClassName(prop.getProperty("driver"));
        druidDataSource.setUrl(prop.getProperty("url"));
        druidDataSource.setUsername(prop.getProperty("user"));
        druidDataSource.setPassword(prop.getProperty("pwd"));

        // 3、设置高级参数, ps:可以看到他有很多很多的方法
        druidDataSource.setInitialSize(10); // 初始化时数据库连接池中只有10个连接对象
        druidDataSource.setMaxActive(100);  // 设置池中的最多的连接对象个数,因为数据库连接池都有自动增长的功能, 但是也得设置它不能无线增长
        druidDataSource.setMinIdle(10); // 设置池中最小的连接对象个数, 因为数据库连接池都有自动释放的功能, 但也得设置它至少保留10个
        
        System.out.println(druidDataSource.getConnectCount()); // 看下有多少个链接对象

        // 4、准备从池中获取链接, 查询数据, 然后再把链接放回去
        Connection conn;
        PreparedStatement pst;
        ResultSet rs;
        try {
            conn = druidDataSource.getConnection();
            pst = conn.prepareStatement("select * from test where id >= ?");
            pst.setInt(1, 2);
            rs = pst.executeQuery();
            while (rs.next()) {
                System.out.println(rs.getString(1) + "\t" + rs.getString(2));  // rs的下标是从1开始
            }
        } catch (SQLException e) {
            e.printStackTrace();
        } finally {
            druidDataSource.close(); // 这个close不是真实的close, 而只是把创建的连接又放回到数据库连接池当中了
        }
    }

    /**
     * 获取属性对象
     *
     * @param filePath 属性文件路径
     * @return 返回属性对象
     * @throws IOException ex
     */
    private static Properties getProp(String filePath) throws IOException {
        Properties prop;
        prop = new Properties();
        prop.load(new FileInputStream(filePath));
        return prop;
    }
}

5、其他的数据库连接池工具
略(因为各个数据库连接池的实现都是大同小异,都是下载jar包,配置properties,然后找个入口类(继承了java的javax.sql.DataSource类的那个类), 然后就可以调用getConnectio()方法从池中获取数据库连接, 然后调用close, 把数据库连接再放回到池中)

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

友情链接更多精彩内容