JDBC连接池的简单实现

首先解释一下,我在做自己android发育。java web这是我的弱点,就在最近,京东云免费,因此,要折腾几。有一点经验,特别是作为共享。

假设内容的文章是错,还请高手指正。

我在这里web结束,需要连接到数据库查询插入其他操作,就断开的话,未免效率太低。

曾经知道tomcat中能够配置,可是京东云引擎的tomcat并不能由自己配置。由于我折腾的东西较小。所以也不考虑使用框架。于是就想自己写一个。

我写的连接池非常easy,在初始化时创建5个连接,并放在一个列表其中。假设要获取连接,从列表中获取,同一时候列表移除,还回来时,列表加入上。

也就是列表保存的是闲置的连接。

假设列表已经为空了。那么推断是否超过最大连接了,没有就创建,有的话就等待。当然,我这里做的是非常easy的实现。所以没有去做等待超时等处理。

代码例如以下:

package com.githang.tucao.web.dbc;

import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.LinkedList;

public class DatabaseConnection {
    private static final String CREATE_TABLE_TWITTER = "CREATE TABLE IF NOT EXISTS twitter (id INTEGER NOT NULL AUTO_INCREMENT PRIMARY KEY, msg varchar(300) not null) DEFAULT CHARSET=utf8";
    final static String HOST = "host";
    final static String PORT = "port";
    final static String DB_NAME = "dbname";
    final static String USERNAME = "username";
    final static String PASSWORD = "password";
    final static String url = "jdbc:mysql://" + HOST + ":" + PORT + "/" + DB_NAME
            + "?useUnicode=true&characterEncoding=utf-8";
    private static final DatabaseConnection instance = new DatabaseConnection();
    private final int INIT_COUNT = 5;
    private final int MAX_COUNT = 30;
    private int count = 0;
    
    private final Object wait = new Object();
    
    private  LinkedList<Connection> CONN_POOL;

    private DatabaseConnection() {
        CONN_POOL = new LinkedList<Connection>();
        try {
            Class.forName("com.mysql.jdbc.Driver");
            for (int i = 0; i < INIT_COUNT; i++) {
                Connection connection = createConnection();
                if(connection != null) {
                    CONN_POOL.add(createConnection());
                    count++;
                }
            }
     //       Connection connection = getConnection();
     //       Statement stmt = connection.createStatement();
     //       stmt.execute(CREATE_TABLE_TWITTER);
     //       stmt.execute("set names 'utf-8'");
     //       stmt.close();
     //       releaseConnection(connection);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    
    public static DatabaseConnection getInstance() {
        return instance;
    }
    
    private static Connection createConnection() {
        try {
            return DriverManager.getConnection(url, USERNAME, PASSWORD);
        } catch (SQLException e) {
            e.printStackTrace();
        }
        return null;
    }

    public Connection getConnection() {
        synchronized (CONN_POOL) {
            while(CONN_POOL.size() > 0) {
                Connection conn = CONN_POOL.removeLast();
                try {
                    if(conn.isValid(1000)) {
                        return conn;
                    } else {
                        count--;
                    }
                } catch (SQLException e) {
                    e.printStackTrace();
                }
            }
            if(count < MAX_COUNT) {
                count++;
                return createConnection();
            } 
            synchronized (wait) {
                try {
                    wait.wait(3000);
                    if(CONN_POOL.size() > 0) {
                        return CONN_POOL.removeLast();
                    }
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }
            }
        }
        return null;
    }

    public void releaseConnection(Connection connection) {
        CONN_POOL.add(connection);
        synchronized (wait) {
            wait.notify();
        }
    }
    
}
当中count用于保存当前连接数(包含闲置和在使用的)。

wait对象用于线程同步锁。主要是获取不到连接而且须要等其它连接被还回来时使用。在getConnection()里面调用 wait,而在releaseConnection()方法中。也就是释放连接时,调用 notify通知其它等待的线程。

另外,在公用的数据库其中。数据库连接一般是不作长连接的。

所以在这里连接池中的连接。可能是已经断开的或者是无效的,所以在在获取连接时必须得到推断有关当前连接仍然有效。如果没有赢。

版权声明:本文博主原创文章。博客,未经同意不得转载。

原文地址:https://www.cnblogs.com/mengfanrong/p/4814156.html