You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何实现动态切换DataSource并复用指定名称数据库连接?

实现连接复用逻辑的方案

核心目标:针对名为"current"的连接,维护一个全局复用的连接实例,仅在连接失效时重新获取;其他连接则每次新建并在使用后关闭。

具体实现步骤

  • 添加类级别的静态变量,用来保存"current"对应的复用连接
  • 获取当前查询的连接名称,判断是否为"current":
    • 若是,检查复用连接是否存在、未关闭且有效,满足条件则直接使用,否则从数据源重新获取并赋值给复用变量
    • 若不是,正常从数据源获取新连接
  • 调整finally块的关闭逻辑:仅关闭非"current"的连接,复用连接保持打开状态供后续使用

修改后的代码示例

// 类级别的复用连接变量,全局共享
private static Connection reusedCurrentConn = null;
private Connection conn = null;
private PreparedStatement stmt = null;
private ResultSet rs = null;
private DataSource ds = null;

public List<Object> searchQuery(String key) {
    List<Object> result = new ArrayList<>();
    // 获取当前查询对应的连接名称
    String connectionName = this.getKey(Integer.parseInt(key)).getConnection().getName();
    
    try {
        ds = (DataSource) Archicon.getResource("jdbc/" + connectionName);
        
        if ("current".equals(connectionName)) {
            // 检查复用连接是否有效:未关闭、可用
            if (reusedCurrentConn == null || reusedCurrentConn.isClosed() || !reusedCurrentConn.isValid(5)) {
                reusedCurrentConn = ds.getConnection();
            }
            conn = reusedCurrentConn;
        } else {
            // 非current连接,每次新建
            conn = ds.getConnection();
        }
        
        stmt = conn.prepareStatement(this.getKey(Integer.parseInt(key)).getSelect().trim());
        // 执行查询并处理结果集(补充业务逻辑)
        rs = stmt.executeQuery();
        while (rs.next()) {
            // 根据实际需求封装结果到result列表
            // result.add(...);
        }
        
    } catch (NamingException | SQLException e) {
        Archicon.getLogger().error("AwpSapNewRepository error: " + e);
    } finally {
        // 关闭结果集
        try {
            if (rs != null) rs.close();
        } catch (SQLException e) {
            Archicon.getLogger().error("AwpSapNewRepository.searchQuery: errore nella chiusura del resultset su " + e);
        }
        
        // 关闭Statement
        try {
            if (stmt != null) stmt.close();
        } catch (SQLException e) {
            Archicon.getLogger().error("AwpSapNewRepository.searchQuery: errore nella chiusura dello statement su " + e);
        }
        
        // 仅关闭非current的连接,复用连接不关闭
        try {
            if (conn != null && !"current".equals(connectionName)) {
                conn.close();
            }
        } catch (SQLException e) {
            Archicon.getLogger().error("AwpSapNewRepository.searchQuery: errore nella chiusura della connessione su " + e);
        }
    }
    return result;
}

关键注意点

  • 连接有效性校验:使用isValid(timeout)方法判断连接是否可用,避免使用已失效的连接
  • 线程安全:如果是多线程环境,需要给复用连接的获取逻辑加锁(如synchronized块),防止并发创建多个连接
  • 资源清理:应用停止时,需手动关闭复用的连接,避免资源泄漏

内容的提问来源于stack exchange,提问作者Alex

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.04 23:10:22