什么是连接?
连接,是我们的编程语言与数据库交互的一种方式。我们经常会听到这么一句话“数据库连接很昂贵“。
有人接受这种说法,却不知道它的真正含义。因此,下面我将解释它究竟是什么。[如果你已经知道了,你可以跳到它的工作原理部分]
创建连接的代码片段:
String connUrl = "jdbc:mysql://your.database.domain/yourDBname";
Class.forName("com.mysql.jdbc.Driver");
Connection con = DriverManager.getConnection (connUrl);
当我们创建了一个Connection对象,它在内部都执行了什么:
1.“DriverManager”检查并注册驱动程序,
2.“com.mysql.jdbc.Driver”就是我们注册了的驱动程序,它会在驱动程序类中调用“connect(url…)”方法。
3. com.mysql.jdbc.Driver的connect方法根据我们请求的“connUrl”,创建一个“Socket连接”,连接到IP为“your.database.domain”,默认端口3306的数据库。
4.创建的Socket连接将被用来查询我们指定的数据库,并最终让程序返回得到一个结果。
为什么昂贵?
现在让我们谈谈为什么说它“昂贵“。
如果创建Socket连接花费的时间比实际的执行查询的操作所花费的时间还要更长。
这就是我们所说的“数据库连接很昂贵”,因为连接资源数是1,它需要每次创建一个Socket连接来访问DB。
因此,我们将使用连接池。
连接池初始化时创建一定数量的连接,然后从连接池中重用连接,而不是每次创建一个新的。
怎样工作?
接下来我们来看看它是如何工作,以及如何管理或重用现有的连接。
我们使用的连接池供应者,它的内部有一个连接池管理器,当它被初始化:
1.它创建连接池的默认大小,比如指定创建5个连接对象,并把它存放在“可用”状态的任何集合或数组中。
例如,代码片段:
...
String connUrl = "jdbc:mysql://your.database.domain/yourDBname";
String driver = "com.mysql.jdbc.Driver";
private Map<java.sql.Connection, String> connectionPool = null;
private void initPool() {
try {
connectionPool = new HashMap<java.sql.Connection, String>();
Class.forName(driver);
java.sql.Connection con = DriverManager.getConnection(dbUrl);
for (int poolInd = poolSize; poolInd < 0; poolInd++) {
connectionPool.put(con, "AVAILABLE");
}
}
...
2.当我们调用connectionProvider.getConnection(),然后它会从集合中获取一个连接,当然状态也会更改为“不可用”。
例如,代码片段:
...
public java.sql.Connection getConnection() throws ClassNotFoundException, SQLException
{
boolean isConnectionAvailable = true;
for (Entry<java.sql.Connection, String> entry : connectionPool.entrySet()) {
synchronized (entry) {
if (entry.getValue()=="AVAILABLE") {
entry.setValue("NOTAVAILABLE");
return (java.sql.Connection) entry.getKey();
}
isConnectionAvailable = false;
}
}
if (!isConnectionAvailable) {
Class.forName(driver);
java.sql.Connection con = DriverManager.getConnection(connUrl);
connectionPool.put(con, "NOTAVAILABLE");
return con;
}
return null;
}
...
例如,代码片段:
...
public void closeConnection(java.sql.Connection connection) throws ClassNotFoundException, SQLException {
for (Entry<java.sql.Connection, String> entry : connectionPool.entrySet()) {
synchronized (entry) {
if (entry.getKey().equals(connection)) {
//Getting Back the conncetion to Pool
entry.setValue("AVAILABLE");
}
}
}
}
...
基本上连接池的实际工作原理就是这样,但也有可能使用不同的方式。
现在,你可能有一个问题,我们是否可以创造我们自己的连接池机制?
我的建议是使用已经存在的连接池机制,像C3P0,DBCP等。
英文原文 , OSChina.NET翻译
转自:http://www.oschina.net/question/157182_72094
======================================================================
以下为个人总结的测试代码:
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import java.util.Map.Entry;
/**
* 数据库连接提供程序
*
* @author MrChu
* @version 1.0
* @date 2014年12月24日
*/
public class ConnectionProvider {
/**
* Connection:数据库连接对象实例,Boolean:标识连接是否可用
* true:可用,false:不可用
*/
private static Map<Connection, Boolean> connectionPool;
/** 最小连接池数量 */
private static int minIdle = 5;
/** 最大连接池数量 */
private static int maxActive = 10;
/* 数据库连接属性 */
private static String driver = "com.mysql.jdbc.Driver";
private static String url = "jdbc:mysql://127.0.0.1:3306/easyjdbc";
private static String user = "root";
private static String password = "123456";
static {
try {
Class.forName(driver);
connectionPool = new HashMap<Connection, Boolean>();
for (int i = 0; i < minIdle; i++) {
connectionPool.put(DriverManager.getConnection(url, user, password), true);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
} catch (SQLException e) {
e.printStackTrace();
}
}
/**
* 从连接池中获取数据库连接,
* 连接不足时创建新连接并放入连接池中。
* @return
* 数据库连接
*/
public static Connection getConnection() {
boolean hasAvailableConnection = true;
for (Entry<Connection, Boolean> connection : connectionPool.entrySet()) {
synchronized(connection) {
if (connection.getValue()) {
connection.setValue(false);
return connection.getKey();
}
hasAvailableConnection = false;
}
}
Connection connection = null;
if (!hasAvailableConnection) {
try {
connection = DriverManager.getConnection(url, user, password);
if (connectionPool.size() < maxActive) {
connectionPool.put(connection, false);
}
} catch (SQLException e) {
e.printStackTrace();
}
}
return connection;
}
/**
* 关闭数据库连接
* @param connection
* 数据库连接实例
*/
public static void closeConnection(Connection connection) {
if (connectionPool.containsKey(connection)) {
connectionPool.put(connection, true);
} else {
try {
connection.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void main(String[] args) {
// 测试连接池最大连接数
for (int i = 0; i < 12; i++) {
Connection connection = getConnection();
System.out.println((i + 1) + "、正在使用的连接:" + connection + "\n");
}
for (Entry<Connection, Boolean> entry : connectionPool.entrySet()) {
System.out.println(entry);
}
// 测试连接池获取、关闭连接
for (Entry<Connection, Boolean> entry : connectionPool.entrySet()) {
System.out.println(entry);
}
Connection connection = getConnection();
System.out.println("\n正在使用的连接:" + connection + "\n");
for (Entry<Connection, Boolean> entry : connectionPool.entrySet()) {
System.out.println(entry);
}
closeConnection(connection);
System.out.println("\n关闭使用的连接:" + connection + "\n");
for (Entry<Connection, Boolean> entry : connectionPool.entrySet()) {
System.out.println(entry);
}
}
}
推荐阅读:
http://www.cnblogs.com/windlaughing/p/3287501.html