给JavaWeb项目(JDBC)添加Druid 连接池

首先导入Jar包,该资源我已经给出了,本文章的绑定资源
在这里插入图片描述

然后将原有的jdbc获取连接改成如下方式:

import com.alibaba.druid.pool.DruidDataSource;
import com.alibaba.druid.pool.DruidDataSourceFactory;
import javax.sql.DataSource;
import java.sql.Connection;
import java.sql.SQLException;
import java.util.Properties;

/** 数据库连接工具(使用Druid连接池) */
public class JdbcUtils {
    private static DruidDataSource dataSource;

    static {
        try {
            // 配置Druid连接池参数
            Properties properties = new Properties();
            properties.put("driverClassName", "com.mysql.cj.jdbc.Driver");
            properties.put("url", "jdbc:mysql://localhost:3306/app_logistics?serverTimezone=GMT%2B8&characterEncoding=utf-8&allowPublicKeyRetrieval=true&useSSL=false");
            properties.put("username", "app_logistics"); // 修改为你的用户名
            properties.put("password", "app_logistics"); // 修改为你的密码

            // 连接池优化参数(根据需求调整)
            properties.put("initialSize", "5");      // 初始连接数
            properties.put("minIdle", "5");           // 最小空闲连接
            properties.put("maxActive", "20");        // 最大活跃连接
            properties.put("maxWait", "30000");       // 获取连接超时时间(毫秒)
            properties.put("timeBetweenEvictionRunsMillis", "60000"); // 检查间隔
            properties.put("minEvictableIdleTimeMillis", "300000");    // 最小空闲时间
            properties.put("validationQuery", "SELECT 1"); // 心跳检测SQL
            properties.put("testWhileIdle", "true");
            properties.put("testOnBorrow", "false");
            properties.put("testOnReturn", "false");

            // 初始化连接池
            dataSource = (DruidDataSource) DruidDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            throw new RuntimeException("Druid连接池初始化失败", e);
        }
    }

    /** 从连接池获取连接 */
    public static Connection getConnection() {
        try {
            return dataSource.getConnection();
        } catch (SQLException e) {
            throw new RuntimeException("获取数据库连接失败", e);
        }
    }

    /** 归还连接(实际是放回连接池)*/
    public static void closeConnection(Connection conn) {
        if (conn != null) {
            try {
                conn.close(); // 实际不会关闭连接,而是归还给连接池
            } catch (SQLException e) {
                e.printStackTrace();
            }
        }
    }
}
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

学长敲代码

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值