姿姿霸霸~~!
          貴在堅持!
          posts - 106,  comments - 50,  trackbacks - 0

          下午沒事做,第一次嘗試著寫數據連接池。
          想到了大概幾點:1.使用單例模式;2.在構造方法中將數據源初始化;3.大概包括幾個方法:init()、destroy()、getConnect()、release()
          代碼如下:
          1.連接池類:

            1public class DBPool {
            2
            3    /**
            4     * 用個集合來裝連接
            5     */

            6    private Vector<Connection> pool;
            7    /**
            8     * 驅動名字
            9     */

           10    private String driverClassName;
           11    /**
           12     * url
           13     */

           14    private String url;
           15    /**
           16     * 用戶名
           17     */

           18    private String userName;
           19    /**
           20     * 密碼
           21     */

           22    private String passWord;
           23    /**
           24     * 連接池大小
           25     */

           26    private int poolSize;
           27
           28    /**
           29     * 單例模式
           30     */

           31    private static DBPool instance = null;
           32
           33    /**
           34     * 獲取對象
           35     * 
           36     * @return
           37     */

           38    public static synchronized DBPool getInstance() {
           39        if (instance == null{
           40            instance = new DBPool();
           41        }

           42        return instance;
           43    }

           44
           45    /**
           46     * 構造方法+初始化
           47     */

           48    private DBPool() {
           49        // DBSourceBean,裝driver,url,username,password和一些初始化方法
           50        DBSourceBean dbSource = new DBSourceBean();
           51
           52        // 將從DBSourceBean獲取的數據源對象的值賦值
           53        this.driverClassName = dbSource.getDriverClassName();
           54        this.url = dbSource.getUrl();
           55        this.userName = dbSource.getUserName();
           56        this.passWord = dbSource.getPassWord();
           57        this.poolSize = dbSource.getPoolSize();
           58
           59        // 初始化
           60        init();
           61    }

           62
           63    /**
           64     * 初始化
           65     */

           66    private void init() {
           67        // 創建大小為連接池大小的Vector
           68        pool = new Vector<Connection>(poolSize);
           69
           70        // 將連接裝到Vector中去
           71        addConnection();
           72    }

           73
           74    /**
           75     * 制造連接池
           76     */

           77    private void addConnection() {
           78        Connection conn = null;
           79        try {
           80            for (int i = 0; i < poolSize; i++{
           81
           82                // 用jakarta commons的db的組件簡化
           83                DbUtils.loadDriver(driverClassName);
           84                // 獲取連接
           85                conn = DriverManager.getConnection(url, userName, passWord);
           86                // 將連接加入到Vector中去
           87                pool.add(conn);
           88
           89            }

           90        }
           catch (Exception e) {
           91            e.printStackTrace();
           92        }

           93    }

           94
           95    /**
           96     * 外部獲取連接使用的方法
           97     * 
           98     * @return
           99     */

          100    public synchronized Connection getConnection() {
          101        if (pool.size() > 0{
          102            Connection conn = pool.get(0);
          103            pool.remove(conn);
          104            return conn;
          105        }
           else {
          106            return null;
          107        }

          108    }

          109
          110    /**
          111     * 銷毀連接池
          112     */

          113    public synchronized void destroy() {
          114        try {
          115            if (pool != null{
          116                for (int i = 0; i < pool.size(); i++{
          117                    ((Connection) pool.get(i)).close();
          118                    pool.remove(i);
          119                }

          120            }

          121        }
           catch (Exception e) {
          122            e.printStackTrace();
          123        }

          124
          125    }

          126
          127    /**
          128     * 釋放一個連接
          129     * 
          130     * @param conn
          131     */

          132    public synchronized void release(Connection conn) {
          133        pool.add(conn);
          134    }

          135    
          136}

          137//set,get方法省略


          2.數據源的bean類
           1public class DBSourceBean {
           2    /**
           3     * 驅動類名
           4     */

           5    private String driverClassName;
           6    /**
           7     * url
           8     */

           9    private String url;
          10    /**
          11     * 用戶名
          12     */

          13    private String userName;
          14    /**
          15     * 密碼
          16     */

          17    private String passWord;
          18    /**
          19     * 連接池大小
          20     */

          21    private int poolSize;
          22
          23    /**
          24     * 讀取配置文件
          25     */

          26    private void readConfig() {
          27        FileInputStream fis = null;
          28        Properties props = null;
          29        String path = "";
          30        try {
          31            path = Thread.currentThread().getContextClassLoader().getResource("").toString();
          32            path += "\\dataSource.properties";
          33            path = path.substring("file:\\".length());
          34            fis = new FileInputStream(path);
          35            props = new Properties();
          36            props.load(fis);
          37            this.driverClassName = props.getProperty("driverClassName");
          38            this.url = props.getProperty("url");
          39            this.userName = props.getProperty("userName");
          40            this.passWord = props.getProperty("passWord");
          41            this.poolSize = Integer.parseInt(StringUtil.nvm(props.getProperty("poolSize"), "1"));
          42        }
           catch (FileNotFoundException e) {
          43            e.printStackTrace();
          44        }
           catch (IOException e) {
          45            e.printStackTrace();
          46        }

          47    }

          48}

          49//set,get方法省略

          3.屬性文件dataSource.properties
          driverClassName=oracle.jdbc.driver.OracleDriver
          userName=scott
          passWord=tiger
          url=jdbc:oracle:thin:@localhost:1521:sure
          poolSize=10

          4.測試類
           1public class TestDB {
           2
           3    public static void main(String[] args) {
           4        
           5        DBPool db = null;
           6        Connection conn = null;
           7        String sql = "select empno,ename from emp";
           8
           9        try {
          10            long first = System.currentTimeMillis();
          11            System.out.println("------111111開始計時-------");
          12            // for (int j = 0; j < 10; j++) {
          13            // QueryRunner qr = new QueryRunner();
          14            // String sql = "select empno,ename from emp";
          15            // List results = (List) qr.query(conn, sql, new MapListHandler());
          16            //            
          17            //            
          18            // for (int i = 0; i < results.size(); i++) {
          19            // Map map = (Map) results.get(i);
          20            // }
          21            // }
          22            for (int i = 0; i < 100; i++{
          23                db = DBPool.getInstance();
          24                conn = db.getConnection();
          25                Statement stmt = conn.createStatement();
          26                ResultSet rs = stmt.executeQuery(sql);
          27                while (rs.next()) {
          28                }

          29                rs.close();
          30                stmt.close();
          31                db.release(conn);
          32            }

          33            long last = System.currentTimeMillis();
          34            System.out.println("------111111共耗時" + (last - first) + "-------");
          35            
          36
          37            /**
          38             * 測試非連接池的
          39             */

          40            String driverName = "oracle.jdbc.driver.OracleDriver";
          41            String url = "jdbc:oracle:thin:@localhost:sure";
          42            String userName = "scott";
          43            String passWord = "tiger";
          44            first = System.currentTimeMillis();
          45            System.out.println("------222222開始計時-------");
          46            for (int i = 0; i < 100; i++{
          47                Class.forName(driverName);
          48                Connection conn1 = DriverManager.getConnection(url, userName,
          49                        passWord);
          50                Statement stmt1 = conn1.createStatement();
          51                ResultSet rs1 = stmt1.executeQuery(sql);
          52                while (rs1.next()) {
          53                }

          54                rs1.close();
          55                conn1.close();
          56                stmt1.close();
          57            }

          58
          59            last = System.currentTimeMillis();
          60            System.out.println("------2222222共耗時" + (last - first) + "-------");
          61
          62        }
           catch (ClassNotFoundException e) {
          63            e.printStackTrace();
          64        }
           catch (SQLException e) {
          65            e.printStackTrace();
          66        }

          67    }

          68}

          69

          5.總結:功能還很不完善,連接池和管理連接池可以分開寫,還有一些其他的欠考慮,數據源可以用xml來存放,等等。。想好了再改
          posted on 2008-07-31 22:16 xrzp 閱讀(236) 評論(0)  編輯  收藏 所屬分類: JAVA

          <2008年7月>
          293012345
          6789101112
          13141516171819
          20212223242526
          272829303112
          3456789

          常用鏈接

          留言簿(4)

          隨筆分類

          隨筆檔案

          好友的blog

          搜索

          •  

          積分與排名

          • 積分 - 117501
          • 排名 - 500

          最新評論

          閱讀排行榜

          評論排行榜

          主站蜘蛛池模板: 莒南县| 乐平市| 罗江县| 谷城县| 惠水县| 冀州市| 通城县| 江都市| 吉林市| 宁强县| 保定市| 肇州县| 正镶白旗| 阜新市| 德格县| 佛冈县| 托克逊县| 仁怀市| 洞口县| 东源县| 农安县| 恩平市| 巍山| 广德县| 元氏县| 吴川市| 佛坪县| 湟源县| 鄂伦春自治旗| 阆中市| 鄯善县| 广宗县| 龙胜| 临猗县| 额敏县| 噶尔县| 英超| 顺昌县| 眉山市| 山东省| 罗源县|