数据库 : [dbcp](2) : dpcp连接池的基本使用

本文详细介绍了如何在SpringBoot项目中配置和使用DBCP连接池,解决部署后无法读取资源文件的问题,提供了获取数据库连接、执行SQL及查询的方法。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

参考

    https://blog.youkuaiyun.com/god_v/article/details/80656827

    spring boot项目打成的 jar包无法获取src/main/resources下文件 - OSCHINA - 中文开源技术交流社区 

获取连接工具类 


import org.apache.commons.dbcp2.BasicDataSourceFactory;
import org.springframework.core.io.ClassPathResource;

import javax.sql.DataSource;
import java.io.File;
import java.io.FileInputStream;
import java.io.InputStream;
import java.net.URL;
import java.sql.*;
import java.util.LinkedList;
import java.util.List;
import java.util.Properties;

/**
 * @Auther: liyue
 * @Date: 2019/4/28 14:17
 * @Description:
 */
public class DbcpUtil {


    private static Properties properties = null;
    private static DataSource dataSource = null;
    private static Connection connection = null;

    static {
        try {
            //获取配置文件,转换成流
            String propertiesPath = "node.properties";
            InputStream in = null;
            try {
                // 开发环境
                URL url = DbcpUtil.class.getClassLoader().getResource(propertiesPath);
                File file = new File(url.getFile());
                in = new FileInputStream(file);
            } catch (Exception e) {

            }
            if (in == null) {
                // 达成jar包部署之后
                ClassPathResource classPathResource = new ClassPathResource(propertiesPath);
                in = classPathResource.getInputStream();
            }
            //创建properties对象
            properties = new Properties();
            //加载流
            properties.load(in);
            //创建dataSource对象
            dataSource = BasicDataSourceFactory.createDataSource(properties);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    public static Connection getConn() {
        try {
            //得到connection对象
            connection = dataSource.getConnection();
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    public static void execute(String sql) {
        try (Connection conn = getConn();
             Statement stmt = conn.createStatement();) {
            stmt.execute(sql);
        } catch (Exception e) {
            System.err.println("sql执行失败:" + sql);
            throw new RuntimeException(e);
        }
    }

    public static List<List<String>> query(String sql) {
        try (Connection conn = getConn();
             Statement stmt = conn.createStatement();) {
            ResultSet rs = stmt.executeQuery(sql);
            ResultSetMetaData resultSetMetaData = rs.getMetaData();
            int column = resultSetMetaData.getColumnCount();
            List<List<String>> result = new LinkedList<>();
            while (rs.next()) {
                List<String> list = new LinkedList<>();
                for (int i = 1; i <= column; i++) {
                    list.add(rs.getString(i));
                }
                result.add(list);
            }
            return result;
        } catch (Exception e) {
            System.err.println("sql执行失败:" + sql);
            throw new RuntimeException(e);
        }
    }

}

配置文件 db.properties


driverClassName=com.mysql.jdbc.Driver

url=jdbc:mysql://localhost:3306/mybd

username=root

password=root

initialSize=30

maxTotal=30

maxIdle=10

minIdle=5

maxWaitMillis=1000

testOnBorrow=true

validationQuery=select 1

配置说明

initialSize  

     初始化连接,连接池启动时创建的初始化连接数量(默认值为0)

maxActive  
     最大活动连接,连接池中可同时连接的最大的连接数(默认值为8)

minIdle 
     最小空闲连接,连接池中最小的空闲的连接数,低于这个数量会被创建新的连接(默认为0,该参数越接近maxIdle,性能越好,因为连接的创建和销毁,都是需要消耗资源的;但是不能太大,因为在机器很空闲的时候,也会创建低于minidle个数的连接,类似于jvm参数中的Xmn设置)

maxIdle   
     最大空闲连接,连接池中最大的空闲的连接数,超过的空闲连接将被释放,如果设置为负数表示不限制(默认为8个,maxIdle不能设置太小,因为假如在高负载的情况下,连接的打开时间比关闭的时间快,会引起连接池中idle的个数上升超过maxIdle,而造成频繁的连接销毁和创建,类似于jvm参数中的Xmx设置)

maxWait 
     从池中取连接的最大等待时间,单位ms.当没有可用连接时,连接池等待连接释放的最大时间,超过该时间限制会抛出异常,如果设置-1表示无限等待(默认为无限)

validationQuery 
     验证使用的SQL语句

testWhileIdle    
     指明连接是否被空闲连接回收器(如果有)进行检验.如果检测失败,则连接将被从池中去除.

testOnBorrow    
     借出连接时不要测试,否则很影响性能。一定要配置,因为它的默认值是true。false表示每次从连接池中取出连接时,不需要执行validationQuery = "SELECT 1" 中的SQL进行测试。若配置为true,对性能有非常大的影响,性能会下降7-10倍。

timeBetweenEvictionRunsMillis
     每30秒运行一次空闲连接回收器,配置timeBetweenEvictionRunsMillis = "30000"后,每30秒运行一次空闲连接回收器(独立线程)。并每次检查3个连接,如果连接空闲时间超过30分钟就销毁。销毁连接后,连接数量就少了,如果小于minIdle数量,就新建连接,维护数量不少于minIdle,过行了新老更替。

minEvictableIdleTimeMillis
     池中的连接空闲30分钟后被回收

numTestsPerEvictionRun
     在每次空闲连接回收器线程(如果有)运行时检查的连接数量

removeAbandoned
     连接泄漏回收参数,当可用连接数少于3个时才执行

removeAbandonedTimeout
     连接泄漏回收参数,180秒,泄露的连接可以被删除的超时值

maven依赖


            <!-- https://mvnrepository.com/artifact/org.apache.commons/commons-dbcp2 -->
            <dependency>
                <groupId>org.apache.commons</groupId>
                <artifactId>commons-dbcp2</artifactId>
                <version>2.6.0</version>
            </dependency>

END。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值