自定义配置数据源 DataSource

本文介绍了一个自定义的数据源类实现,该类通过模拟数据库连接池的方式提供连接复用,有效提高数据库操作效率。文章包括了自定义数据源类、工具类以及配置文件的详细代码,并提供了一个简单的测试类来验证连接池的功能。

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

1 . 直接看代码
自定义数据源类

package com.qf.ds;
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;

import javax.sql.DataSource;

import com.qf.utils.DBUtils;


/**
 * 数据源的目的是: 为了得到连接。而且这些连接可以复用
 * 
 * 数据源中要模拟数据库连接池 (LinkedList)
 * @author Administrator
 */
public class MyDataSource  implements DataSource{

    //模拟就是一个连接池 ,默认放10个
    private  static  LinkedList<Connection> pool =new LinkedList<Connection>();
    static {
        for (int i = 0; i < 10; i++) {
            Connection connection = DBUtils.getConnection();
            pool.add(connection);
        }
    } 
    @Override
    public Connection getConnection() throws SQLException {
        // TODO Auto-generated method stub

        if (pool!=null&&pool.size()>0) {
            System.out.println("=====getConnection=====");
            Connection connection =  pool.removeFirst();
            return connection;
        }
        return null;
    }

    /**
     * 连接使用完毕直接放回到连接池
     */
    public  void release(Connection connection ) {
        try {
            System.out.println("=====release=====");
            pool.addLast(connection);
        } catch (Exception e) {
            // TODO: handle exception
        }
    }

    @Override
    public PrintWriter getLogWriter() throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public void setLogWriter(PrintWriter out) throws SQLException {
        // TODO Auto-generated method stub

    }

    @Override
    public void setLoginTimeout(int seconds) throws SQLException {
        // TODO Auto-generated method stub

    }

    @Override
    public int getLoginTimeout() throws SQLException {
        // TODO Auto-generated method stub
        return 0;
    }

    @Override
    public Logger getParentLogger() throws SQLFeatureNotSupportedException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public <T> T unwrap(Class<T> iface) throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public boolean isWrapperFor(Class<?> iface) throws SQLException {
        // TODO Auto-generated method stub
        return false;
    }

    @Override
    public Connection getConnection(String username, String password) throws SQLException {
        // TODO Auto-generated method stub
        return null;
    }


}

2 . 工具类

package com.qf.utils;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ResourceBundle;

public class DBUtils {
    private static String driverClass = "";
    private static String url = "";
    private static String user = "";
    private static String pwd = "";
    static {
        ResourceBundle resourceBundle = ResourceBundle.getBundle("dbinfo");
        driverClass = resourceBundle.getString("driverClass");
        url = resourceBundle.getString("url");
        user = resourceBundle.getString("user");
        pwd = resourceBundle.getString("password");
    }

    public static Connection getConnection() {
        Connection connection = null;
        // 1.注册驱动
        try {
            Class.forName(driverClass);

        } catch (ClassNotFoundException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("数据库驱动异常");
        }

        // 2.得到连接
        try {
            connection = DriverManager.getConnection(url, user, pwd);
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
            System.out.println("数据库连接异常");
        }
        return connection;
    }


    public  static void closeAll(ResultSet resultSet,Statement  statement,   Connection connection) {
          if (resultSet!=null) {
              try {
                resultSet.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
          if (statement!=null) {
              try {
                  statement.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
          if (connection!=null) {
              try {
                 connection.close();
            } catch (SQLException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    }
}

properties配置文件

driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://localhost:3306/1713_transaction
user=root
password=123

3 . 测试类

package com.qf.utils;

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

import org.junit.Test;

import com.qf.ds.MyDataSource;

public class Test01 {

    @Test
    public void test01() {
        //1.从数据源的连接池中获取连接
        MyDataSource  ds = new MyDataSource(); 
        Connection connection = null ;
        try {
            connection = ds.getConnection();
            System.out.println(connection);
            PreparedStatement preparedStatement = connection.prepareStatement("select * from user");
            ResultSet resultSet = preparedStatement.executeQuery();
            while(resultSet.next()) {
                 System.out.println(resultSet.getString("name"));;
             }
        } catch (SQLException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }finally {
            if (connection!=null) {
                ds.release(connection);
            }
        }   
    }
}

这个只需要添加数据库驱动jar包

### 自定义配置 HikariDataSource 的方法 在 Java 项目中,`HikariCP` 是一种高性能 JDBC 连接池库。为了自定义 `HikariDataSource` 配置,在创建数据源实例时可以设置多个属性来优化数据库连接管理。 #### 创建并配置 HikariDataSource 实例 下面是一个简单的例子展示如何通过编程方式来自定义配置 `HikariDataSource`: ```java import com.zaxxer.hikari.HikariConfig; import com.zaxxer.hikari.HikariDataSource; public class DataSourceExample { public static void main(String[] args) throws Exception { // Create a HikariConfig instance to set properties. HikariConfig config = new HikariConfig(); // Set required connection pool settings config.setJdbcUrl("jdbc:mysql://localhost:3306/mydb"); config.setUsername("root"); config.setPassword("password"); // Customize additional configurations as needed config.setMaximumPoolSize(10); // 设置最大连接数 config.setMinimumIdle(5); // 设置最小空闲连接数 config.setIdleTimeout(30000L); // 设置空闲超时时长 (毫秒) config.setMaxLifetime(1800000L); // 设置单个连接的最大生命周期 (毫秒) // Optionally specify driverClassName if not auto-detected by URL config.setDriverClassName("com.mysql.cj.jdbc.Driver"); // Initialize the data source with these settings HikariDataSource dataSource = new HikariDataSource(config); // Use the configured data source... try (var conn = dataSource.getConnection()) { System.out.println("Connection established."); } finally { // Close the data source when done dataSource.close(); } } } ``` 此代码片段展示了如何初始化一个新的 `HikariConfig` 对象,并为其指定必要的参数如 JDBC URL、用户名和密码等基本信息[^1]。除此之外还设置了几个重要的性能调优选项,比如最大/最小吃用线程数量以及连接存活时间限制等。 对于更复杂的场景,还可以考虑将这些配置项放在外部文件中(例如 application.properties 或者 yaml 文件),以便于管理和维护不同环境下的差异化的配置需求。
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值