本次作业通过用阿里的druid来优化数据库连接程序。

将从官网下载下的druid-1.2.23.jar和mysql-connector-java-8.0.21.jar导入项目工程。

具体导入方式参考我先前发布的java 后端练习作业 20250925

构建属性:

在src目录下创建druid.properties文件,并写入参数:

url=jdbc:mysql://localhost:3306/myweb?useSSL=false&serverTimezone=UTC&useUnicode=true&characterEncoding=UTF-8
username=root
password=yourpassword
driverClassName=com.mysql.cj.jdbc.Driver


initialSize=3
minIdle=3
maxActive=15
maxWait=8000


validationQuery=SELECT 1
testWhileIdle=true
testOnBorrow=false
testOnReturn=false
timeBetweenEvictionRunsMillis=60000
minEvictableIdleTimeMillis=300000


poolPreparedStatements=true
maxPoolPreparedStatementPerConnectionSize=20

前四个定义了连接数据库所需的参数。

然后下面四个定义了连接的初始化,最小空闲,最大值,等待时间

然后定义了多个用于测试连接池是否正常运作的参数

最后定义了两个用于优化ps的参数

编写DBUtil.java:

package MyWork.chp03.utils;
import com.mysql.cj.jdbc.MysqlDataSource;
import javax.sql.*;
import java.sql.*;
import java.io.*;
import java.util.*;

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
public class DBUtil {
    private static volatile DataSource dataSource;

    private static DataSource getDataSource() {
        if (dataSource == null) {
            synchronized (DBUtil.class) {
                if (dataSource == null) {
                    try (InputStream in = DBUtil.class.getClassLoader()
                            .getResourceAsStream("druid.properties")) {
                        if (in != null) {
                            Properties props = new Properties();
                            props.load(in);
                            dataSource = DruidDataSourceFactory.createDataSource(props);
                        }
                    } catch (Exception e) {
                        throw new RuntimeException("初始化Druid连接池失败", e);
                    }
                }
            }
        }
        return dataSource;
    }

    public static Connection getConnection() throws SQLException {
        return getDataSource().getConnection();
    }

    public static void close(Connection conn, Statement stmt, ResultSet rs) {
        if (rs != null) try { rs.close(); } catch (SQLException ignored) {}
        if (stmt != null) try { stmt.close(); } catch (SQLException ignored) {}
        if (conn != null) try { conn.close(); } catch (SQLException ignored) {}
    }
    public static void shutdown() {
        DataSource ds = dataSource;
        if (ds instanceof DruidDataSource) {
            ((DruidDataSource) ds).close();
        }
    }
}

这里通过inputStream输入流的方式保存properties中的数据,并用properties类将数据格式化,变为键值对。最后通过相关语句使用druid获取到dataSource。

Logo

Agent 垂直技术社区,欢迎活跃、内容共建。

更多推荐