为什么不在try{}catch内,一捕捉到连接异常就处理呢,何必定时检查。

解决方案 »

  1.   


    我觉得你的想法最大的困难在于收回连接的问题,你光凭时间长短来收回连接,似乎不当,如果一个连接此时正在用,你把它收回,势必断开了它的连接,肯定出错的。如何知道它此时正活动呢?不可能的。我以前也有同样的想法,但最终我还是放弃了,我只是在编码中注意到随时关闭不用的连接。
    并且所有的连接数据库的语句集中在一起。保证了不会有忘记关闭的连接。仅此而已。欢迎与我讨论 [email protected]
      

  2.   

    当然不能放在try{}catch块内。比如在JSP中请求一个连接,分配给它后一个连接,标记为已分配,当用户使用这个连接对象提交数据时发生网络连接故障,而没执行到把个收回的函数,这个连接就成了一个废弃的连接,我必须判断超出一个最大时间就收回它,这个时间我设置的稍长一些,保证在这个时间内对数据操作肯定够用!比如超过10分钟就把它定为废弃的而收回,我想所有的操作都用不了10分钟,这样就会保证不会收回正在被使用的连接!!!如果不这样检查,当每次出现那些网络故障或用户中途取消数据操作而没执行收回函数就废弃一个连接,时间长了连接就会全被标记为已分配!!!所以必须检查,现在只是难在如何把与这个连接所有关联都取消,让它还可以像刚建立时那样正确使用!!!QQ13232654,欢迎讨论,谢谢支持!!!!
      

  3.   

    我不知道你是如何实现这个连接池的,我用的是一个网上比较流行的源代码:
    不知你是否看过。先帖给你吧。
    /*
     * 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.
     *
     *
     * 2001-01-11 Modified by yancheng()
     * 1.move "db.properties" to web-inf/classes/conf/db.properties
     * 2.add "package DbUtil".
     *
     */package stat.DbUtil;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 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 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("/conf/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/conf/");
                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 Connection getConnection() {
                Connection con = null;
                if (freeConnections.size() > 0) {
                    // Pick the first Connection in the Vector
                    // to get round-robin usage
                    con = (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 Connection getConnection(long timeout) {
                long startTime = new Date().getTime();
                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()) {
                    Connection con = (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 Connection newConnection() {
                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;
            }
        }
    }
      

  4.   

    try
    {
     ...
    }
    catch(Exception e)
    {
     ...
    }
    finally
    {
     ...
    }
      

  5.   

    谢谢sharetop(天生很笨)老兄的热心!!!但还是解决不了我的问题!skyyoung(路人甲)您的这种建议我在上面已经回复了,根本行不通!!!谢谢
      

  6.   


    我理解你的意思,你是问connection可以close,但是createStatement出来的Statement如何close吧?我以前的想法也有这个问题。我在自定义的类PooledSQL中定义了方法free就涉及到如何关闭connection和statement的问题。结果我把statement也作为这个类的成员变量了。同样,你也可以这样:上面的代码是把空闲的连接放在一个Vector中,如果这样,你要把所有用到的连接也放在一个vector中,并且记录它的申请时间。用hashtable吧,一个connection,一个date,一个statement,作为vector的一个元素。在你分配一个connection时,同时生成它的Statement,取出当前时间一起放入vector中。
    要用的话,你有了statement就行了。然后你在一个线程里,不时检查这个vector,如果有一个connection的申请时间过长,把这个connection和statement都关闭,即可。如何?你再考虑一下吧。
      

  7.   

    sharetop(天生很笨)老兄说到点子上了,这是目前解决这个问题的最好方法,真的很感谢!!这样实际分分配出去的就是statement对象,就可以在后台控制了!!!还有个问题想问问,一个javabean如何在tomcat等服务器启动时就能进行某些初始化,servlet就可以,如果我写成sevlet而不覆盖它的service等等方法,写别的方法,只用它的初始化功能,在JSP中像javabean一样调用它的方法呢????再次感谢!!!
      

  8.   

    connection倒是没有必要关闭,只要关闭了由它生成的statement对象这个con还是可以再分配使用的!!!补充一下!!!
      

  9.   


    你想,javabean只是一个组件而已,又不能独立运行,你说的初始化是什么意思?new它?
    那你在一个servlet的init方法中new它不就行了吗?你说的写一个servlet来用,我觉得应该可行,不过我没试过,你试一下吧。
      

  10.   

    sharetop(天生很笨),我在另一个贴子里已经给你加分了,就不多给了哟!!!!呵呵