JDBC Connection Pool Example

该博客介绍了DBConnectionManager类,它是一个单例类,用于管理数据库连接池。通过该类,客户端可从连接池获取和归还连接,还能在关闭时释放所有连接。它依据属性文件创建连接池,处理连接的获取、释放等操作,确保连接的有效管理。

 

/*
 * Copyright (c) 1998 by Gefion software.
 *
 * Permission to use, copy, and distribute this software for
 * NON-COMMERCIAL purposes and without fee is hereby granted
 * provided that this copyright notice appears in all copies.
 *
 */

import java.io.*;
import java.sql.*;
import java.util.*;
import java.util.Date;

/**
 * This class is a Singleton that provides access to one or many
 * connection pools defined in a Property file. A client gets
 * access to the single instance through the static getInstance()
 * method and can then check-out and check-in connections from a pool.
 * When the client shuts down it should call the release() method
 * to close all open connections and do other clean up.
 */
public class DBConnectionManager {
    static private DBConnectionManager instance;       // The single instance
    static private int clients;

    private Vector drivers = new Vector();
    private PrintWriter log;
    private Hashtable pools = new Hashtable();
   
    /**
     * Returns the single instance, creating one if it's the
     * first time this method is called.
     *
     * @return DBConnectionManager The single instance.
     */
    static synchronized public DBConnectionManager getInstance() {
        if (instance == null) {
            instance = new DBConnectionManager();
        }
        clients++;
        return instance;
    }
   
    /**
     * A private constructor since this is a Singleton
     */
    private DBConnectionManager() {
        init();
    }
   
    /**
     * Returns a connection to the named pool.
     *
     * @param name The pool name as defined in the properties file
     * @param con The Connection
     */
    public void freeConnection(String name, Connection con) {
        DBConnectionPool pool = (DBConnectionPool) pools.get(name);
        if (pool != null) {
            pool.freeConnection(con);
        }
    }
       
    /**
     * Returns an open connection. If no one is available, and the max
     * number of connections has not been reached, a new connection is
     * created.
     *
     * @param name The pool name as defined in the properties file
     * @return Connection The connection or null
     */
    public java.sql.Connection getConnection(String name) {
        DBConnectionPool pool = (DBConnectionPool) pools.get(name);
        if (pool != null) {
            return pool.getConnection();
        }
        return null;
    }
   
    /**
     * Returns an open connection. If no one is available, and the max
     * number of connections has not been reached, a new connection is
     * created. If the max number has been reached, waits until one
     * is available or the specified time has elapsed.
     *
     * @param name The pool name as defined in the properties file
     * @param time The number of milliseconds to wait
     * @return Connection The connection or null
     */
    public java.sql.Connection getConnection(String name, long time) {
        DBConnectionPool pool = (DBConnectionPool) pools.get(name);
        if (pool != null) {
            return pool.getConnection(time);
        }
        return null;
    }
   
    /**
     * Closes all open connections and deregisters all drivers.
     */
    public synchronized void release() {
        // Wait until called by the last client
        if (--clients != 0) {
            return;
        }
       
        Enumeration allPools = pools.elements();
        while (allPools.hasMoreElements()) {
            DBConnectionPool pool = (DBConnectionPool) allPools.nextElement();
            pool.release();
        }
        Enumeration allDrivers = drivers.elements();
        while (allDrivers.hasMoreElements()) {
            Driver driver = (Driver) allDrivers.nextElement();
            try {
                DriverManager.deregisterDriver(driver);
                log("Deregistered JDBC driver " + driver.getClass().getName());
            }
            catch (SQLException e) {
                log(e, "Can't deregister JDBC driver: " + driver.getClass().getName());
            }
        }
    }
   
    /**
     * Creates instances of DBConnectionPool based on the properties.
     * A DBConnectionPool can be defined with the following properties:
     * <PRE>
     * &lt;poolname&gt;.url         The JDBC URL for the database
     * &lt;poolname&gt;.user        A database user (optional)
     * &lt;poolname&gt;.password    A database user password (if user specified)
     * &lt;poolname&gt;.maxconn     The maximal number of connections (optional)
     * </PRE>
     *
     * @param props The connection pool properties
     */
    private void createPools(Properties props) {
        Enumeration propNames = props.propertyNames();
        while (propNames.hasMoreElements()) {
            String name = (String) propNames.nextElement();
            if (name.endsWith(".url")) {
                String poolName = name.substring(0, name.lastIndexOf("."));
                String url = props.getProperty(poolName + ".url");
                if (url == null) {
                    log("No URL specified for " + poolName);
                    continue;
                }
                String user = props.getProperty(poolName + ".user");
                String password = props.getProperty(poolName + ".password");
                String maxconn = props.getProperty(poolName + ".maxconn", "0");
                int max;
                try {
                    max = Integer.valueOf(maxconn).intValue();
                }
                catch (NumberFormatException e) {
                    log("Invalid maxconn value " + maxconn + " for " + poolName);
                    max = 0;
                }
                DBConnectionPool pool =
                    new DBConnectionPool(poolName, url, user, password, max);
                pools.put(poolName, pool);
                log("Initialized pool " + poolName);
            }
        }
    }
   
    /**
     * Loads properties and initializes the instance with its values.
     */
    private void init() {
        InputStream is = getClass().getResourceAsStream("/db.properties");
        Properties dbProps = new Properties();
        try {
            dbProps.load(is);
        }
        catch (Exception e) {
            System.err.println("Can't read the properties file. " +
                "Make sure db.properties is in the CLASSPATH");
            return;
        }
        String logFile = dbProps.getProperty("logfile", "DBConnectionManager.log");
        try {
            log = new PrintWriter(new FileWriter(logFile, true), true);
        }
        catch (IOException e) {
            System.err.println("Can't open the log file: " + logFile);
            log = new PrintWriter(System.err);
        }
        loadDrivers(dbProps);
        createPools(dbProps);
    }
   
    /**
     * Loads and registers all JDBC drivers. This is done by the
     * DBConnectionManager, as opposed to the DBConnectionPool,
     * since many pools may share the same driver.
     *
     * @param props The connection pool properties
     */
    private void loadDrivers(Properties props) {
        String driverClasses = props.getProperty("drivers");
        StringTokenizer st = new StringTokenizer(driverClasses);
        while (st.hasMoreElements()) {
            String driverClassName = st.nextToken().trim();
            try {
                Driver driver = (Driver)
                    Class.forName(driverClassName).newInstance();
                DriverManager.registerDriver(driver);
                drivers.addElement(driver);
                log("Registered JDBC driver " + driverClassName);
            }
            catch (Exception e) {
                log("Can't register JDBC driver: " +
                    driverClassName + ", Exception: " + e);
            }
        }
    }
   
    /**
     * Writes a message to the log file.
     */
    private void log(String msg) {
        log.println(new Date() + ": " + msg);
    }
   
    /**
     * Writes a message with an Exception to the log file.
     */
    private void log(Throwable e, String msg) {
        log.println(new Date() + ": " + msg);
        e.printStackTrace(log);
    }
   
    /**
     * This inner class represents a connection pool. It creates new
     * connections on demand, up to a max number if specified.
     * It also makes sure a connection is still open before it is
     * returned to a client.
     */
    class DBConnectionPool {
        private int checkedOut;
        private Vector freeConnections = new Vector();
        private int maxConn;
        private String name;
        private String password;
        private String URL;
        private String user;
       
        /**
         * Creates new connection pool.
         *
         * @param name The pool name
         * @param URL The JDBC URL for the database
         * @param user The database user, or null
         * @param password The database user password, or null
         * @param maxConn The maximal number of connections, or 0
         *   for no limit
         */
        public DBConnectionPool(String name, String URL, String user, String password,
                int maxConn) {
            this.name = name;
            this.URL = URL;
            this.user = user;
            this.password = password;
            this.maxConn = maxConn;
        }
       
        /**
         * Checks in a connection to the pool. Notify other Threads that
         * may be waiting for a connection.
         *
         * @param con The connection to check in
         */
        public synchronized void freeConnection(Connection con) {
            // Put the connection at the end of the Vector
            freeConnections.addElement(con);
            checkedOut--;
            notifyAll();
        }
       
        /**
         * Checks out a connection from the pool. If no free connection
         * is available, a new connection is created unless the max
         * number of connections has been reached. If a free connection
         * has been closed by the database, it's removed from the pool
         * and this method is called again recursively.
         */
        public synchronized java.sql.Connection getConnection() {
            java.sql.Connection con = null;
            if (freeConnections.size() > 0) {
                // Pick the first Connection in the Vector
                // to get round-robin usage
                con = (java.sql.Connection) freeConnections.firstElement();
                freeConnections.removeElementAt(0);
                try {
                    if (con.isClosed()) {
                        log("Removed bad connection from " + name);
                        // Try again recursively
                        con = getConnection();
                    }
                }
                catch (SQLException e) {
                    log("Removed bad connection from " + name);
                    // Try again recursively
                    con = getConnection();
                }
            }
            else if (maxConn == 0 || checkedOut < maxConn) {
                con = newConnection();
            }
            if (con != null) {
                checkedOut++;
            }
            return con;
        }
       
        /**
         * Checks out a connection from the pool. If no free connection
         * is available, a new connection is created unless the max
         * number of connections has been reached. If a free connection
         * has been closed by the database, it's removed from the pool
         * and this method is called again recursively.
         * <P>
         * If no connection is available and the max number has been
         * reached, this method waits the specified time for one to be
         * checked in.
         *
         * @param timeout The timeout value in milliseconds
         */
        public synchronized java.sql.Connection getConnection(long timeout) {
            long startTime = new Date().getTime();
            java.sql.Connection con;
            while ((con = getConnection()) == null) {
                try {
                    wait(timeout);
                }
                catch (InterruptedException e) {}
                if ((new Date().getTime() - startTime) >= timeout) {
                    // Timeout has expired
                    return null;
                }
            }
            return con;
        }
       
        /**
         * Closes all available connections.
         */
        public synchronized void release() {
            Enumeration allConnections = freeConnections.elements();
            while (allConnections.hasMoreElements()) {
                java.sql.Connection con = (java.sql.Connection) allConnections.nextElement();
                try {
                    con.close();
                    log("Closed connection for pool " + name);
                }
                catch (SQLException e) {
                    log(e, "Can't close connection for pool " + name);
                }
            }
            freeConnections.removeAllElements();
        }
       
        /**
         * Creates a new connection, using a userid and password
         * if specified.
         */
        private java.sql.Connection newConnection() {
            java.sql.Connection con = null;
            try {
                if (user == null) {
                    con = DriverManager.getConnection(URL);
                }
                else {
                    con = DriverManager.getConnection(URL, user, password);
                }
                log("Created a new connection in pool " + name);
            }
            catch (SQLException e) {
                log(e, "Can't create a new connection for " + URL);
                return null;
            }
            return con;
        }
    }
}

<think>嗯,用户问的是如何在JMeter的JDBC Request中进行shared设置,配置方法和作用。首先,我需要回忆一下JMeter的相关知识。记得JDBC Connection Configuration是用来配置数据库连接的,而JDBC Request是用来执行SQL查询的。shared设置应该涉及到连接池的共享方式吧? 用户提供的引用里,引用[3]提到Variable Name需要和JDBC Connection Configuration里的名字一致,还有关于参数化的一些内容。但shared设置具体在哪儿呢?可能需要查看JMeter的界面或者文档。 我记得JDBC Connection Configuration有一个选项叫“Connection Pool Configuration”,里面有几个参数,比如Max Number of Connections,还有Test While Idle之类的。但shared的设置可能是在JDBC Request元件里?或者是在连接配置那里? 然后,JDBC Request的shared设置应该控制连接池的使用范围。比如,是否每个线程有自己的连接,或者线程组共享,或者跨线程组共享。通常,JMeter元件的作用域有线程内、线程组、全局等选项。shared可能指的是这个作用域设置。 在JDBC Request的配置中,应该有一个下拉菜单选择shared的方式,比如选择“All threads”或者“Current thread group”。不同的设置会影响并发测试时的连接使用情况。比如,如果设置为“All threads”,那么所有线程组共享同一个连接池,可能会导致连接数不足的问题,需要合理配置最大连接数。 作用方面,shared设置的作用主要是控制数据库连接的共享范围,从而影响测试的性能和资源使用。比如,每个线程独立使用连接的话,可能会增加数据库负担,但更接近真实场景;而共享连接则可以减少资源消耗,但可能影响测试结果的准确性。 另外,用户提到的引用[4]中的错误可能和连接配置有关,比如SSL设置或者公钥检索问题,但shared设置可能不直接相关。不过如果连接池配置不当,比如最大连接数不够,可能会导致连接超时或无法获取连接的错误,这时候调整shared设置和连接数可能有帮助。 总结一下,shared设置的配置方法是在JDBC Request中选择合适的共享模式,比如线程、线程组或全局,作用是根据测试需求合理分配数据库连接资源,避免过多连接导致数据库压力过大或者连接不足的问题。同时需要结合JDBC Connection Configuration中的连接池参数,如最大连接数,来优化测试性能。</think>### JDBC Request中shared配置方法及作用 #### 一、shared配置方法 1. **定位参数位置** 在JMeter的JDBC Request元件中,找到 **`Variable Name`** 下方的 **`Shared Settings`** 区域,包含三个选项: - `All Threads`(所有线程共享连接池) - `Current Thread Group`(仅当前线程组共享连接池) - `Edit`(自定义作用域) ![JDBC Request Shared Settings示意图](https://example.com/jmeter-jdbc-shared-settings.png) [^3] 2. **配置步骤** 1. 确保JDBC Connection Configuration的`Variable Name`与JDBC Request中引用的名称一致[^3]。 2. 根据测试需求选择共享模式: - **`All Threads`**:跨线程组共享连接池,适用于全局数据库操作。 - **`Current Thread Group`**:仅在当前线程组内共享,避免多线程组竞争连接资源。 - **`Edit`**:手动指定作用域(需输入作用域标识符)。 3. **连接池参数联动** 需在JDBC Connection Configuration中设置`Max Number of Connections`,避免共享模式下连接数不足导致超时[^1]。 --- #### 二、shared配置作用 1. **资源优化** - `All Threads`模式下,所有线程共享同一连接池,减少数据库连接创建开销,但需注意并发数不超过最大连接数。 - `Current Thread Group`模式下,不同线程组隔离连接池,避免资源冲突。 2. **场景适配** - **压力测试**:推荐`All Threads`模式,模拟高并发下数据库连接复用。 - **功能隔离**:使用`Current Thread Group`模式,确保不同测试模块独立运行[^2]。 3. **错误规避** 若出现`Public Key Retrieval`错误(如引用[4]),可尝试在JDBC URL中添加`allowPublicKeyRetrieval=true`,并调整共享模式以减少连接竞争。 --- #### 三、配置示例 ```sql # JDBC Connection Configuration jdbc:mysql://localhost:3306/test?useSSL=false&allowPublicKeyRetrieval=true ``` | 参数 | 值 | |-----------------------|-----------------| | Variable Name | mysql_pool | | Max Connections | 50 | | Shared Settings | All Threads | ---
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值