數據庫連接池的概念
-
數據庫連接背景
- 數據庫連接是一種關鍵的、有限的、昂貴的資源,這一點在多用戶的網頁應用程序中體現得尤為突出。對數據庫連接的管理能顯著影響到整個應用程序的伸縮性和健壯性,影響到程序的性能指標。數據庫連接池正是針對這個問題提出來的。
-
數據庫連接池
- 數據庫連接池負責分配、管理和釋放數據庫連接,它允許應用程序重復使用一個現有的數據庫連接,而不是再重新建立一個。這項技術能明顯提高對數據庫操作的性能。
-
數據庫連接池的原理
-
沒有使用數據庫連接池:一個訪問創建一個連接,使用完關閉連接。而頻繁的創建和關閉連接非常耗時
-
使用數據庫連接池之后:提前准備一些數據庫連接,使用時從池中取出,用完歸還連接池
-
自定義連接池
初探連接池
自定義JDBC工具類
配置文件 config.properties
driverClass=com.mysql.jdbc.Driver
url=jdbc:mysql://主機名:3306/數據庫名
username=用戶名
password=密碼
JDBCUtils工具類
public class JDBCUtils {
private JDBCUtils() {} //構造函數私有化
private static String driverClass;
private static String url;
private static String username;
private static String password;
private static Connection con;
static {
try {
InputStream is = JDBCUtils.class.getClassLoader().getResourceAsStream("config.properties");
Properties properties = new Properties();
properties.load(is);
driverClass = properties.getProperty("driverClass");
url = properties.getProperty("url");
username = properties.getProperty("username");
password = properties.getProperty("password");
Class.forName(driverClass);
} catch (IOException e) {
e.printStackTrace();
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
}
public static Connection getConnection() { //獲取連接對象
try {
con = DriverManager.getConnection(url, username, password);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
//關閉連接(有查詢結果集)
public static void close(Connection con, Statement stat, ResultSet res) {
if (con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if (res != null) {
try {
res.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
//關閉連接(無查詢結果集)
public static void close(Connection con, Statement stat) {
close(con, stat, null);
}
}
實現連接池類
定義一個連接池類並實現java.sql.DataSource
接口。
Connection getConnection(); //獲取數據庫連接對象
public class MyDataSource implements DataSource{
//定義集合容器,用於保存多個數據庫連接對象
//使用Collections 工具類實現集合的線程同步
private static List<Connection> pool = Collections.synchronizedList(new ArrayList<Connection>());
//靜態代碼塊,生成10個數據庫連接保存到集合中
static {
for (int i = 0; i < 10; i++) {
Connection con = JDBCUtils.getConnection();
pool.add(con);
}
}
//返回連接池的大小
public int getSize() {
return pool.size();
}
//從池中返回一個數據庫連接
@Override
public Connection getConnection() {
if(pool.size() > 0) {
//從池中獲取數據庫連接
return pool.remove(0);
}else {
throw new RuntimeException("連接數量已用盡");
}
}
@Override
public Connection getConnection(String username, String password) throws SQLException {
return null;
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return null;
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return false;
}
@Override
public PrintWriter getLogWriter() throws SQLException {
return null;
}
@Override
public void setLogWriter(PrintWriter out) throws SQLException {
}
@Override
public void setLoginTimeout(int seconds) throws SQLException {
}
@Override
public int getLoginTimeout() throws SQLException {
return 0;
}
@Override
public Logger getParentLogger() throws SQLFeatureNotSupportedException {
return null;
}
}
自定義連接池的測試
public class MyDataSourceTest {
public static void main(String[] args) throws SQLException {
MyDataSource dataSource = new MyDataSource();
System.out.println("使用前連接池數量:" + dataSource.getSize());
Connection con = dataSource.getConnection();
String sql = "select * from emp";
PreparedStatement pst = con.prepareStatement(sql);
ResultSet res = pst.executeQuery();
while (res.next()) {
String ename = res.getString("ename");
String job = res.getString("job");
String hiredate = res.getString("hiredate");
System.out.println("ename:" + ename + "\t job:" + job + "\t hiredate:" + hiredate);
}
res.close();
pst.close();
con.close();
System.out.println("使用后連接池數量:" + dataSource.getSize());
}
}
輸出:
使用前連接池數量:10
ename:SMITH job:CLERK hiredate:1980-12-17
ename:ALLEN job:SALESMAN hiredate:1981-02-20
ename:WARD job:SALESMAN hiredate:1981-02-22
ename:JONES job:MANAGER hiredate:1981-04-02
ename:MARTIN job:SALESMAN hiredate:1981-09-28
ename:BLAKE job:MANAGER hiredate:1981-05-01
ename:CLARK job:MANAGER hiredate:1981-06-09
ename:SCOTT job:ANALYST hiredate:1987-04-19
ename:KING job:PRESIDENT hiredate:1981-11-17
ename:TURNER job:SALESMAN hiredate:1981-09-08
ename:ADAMS job:CLERK hiredate:1987-05-23
ename:JAMES job:CLERK hiredate:1981-12-03
ename:FORD job:ANALYST hiredate:1981-12-03
ename:MILLER job:CLERK hiredate:1982-01-23
使用后連接池數量:9
問題:雖然我們自定義了數據庫連接池,但是連接關閉以后並沒有歸還給數據庫連接池,還需要改進歸還連接
的問題
繼承方式改進連接池
System.out.println(JDBCUtils.getConnection());
//com.mysql.jdbc.JDBC4Connection@470e2030
通過輸出Connection
的地址發現Connection
類的實現類是JDBC4Connection
,是否能夠通過編寫一個類繼承JDBC4Connection
,然后重寫close()
方法,在關閉連接的同時歸還連接?
/*
自定義Connection類
*/
public class MyConnection1 extends JDBC4Connection {
//聲明連接對象和連接池集合對象
private Connection con;
private List<Connection> pool;
//通過構造方法給成員變量賦值
public MyConnection1(String hostToConnectTo, int portToConnectTo, Properties info, String databaseToConnectTo, String url,Connection con,List<Connection> pool) throws SQLException {
super(hostToConnectTo, portToConnectTo, info, databaseToConnectTo, url);
this.con = con;
this.pool = pool;
}
//重寫close()方法,將連接歸還給池中
@Override
public void close() throws SQLException {
pool.add(con);
}
}
但是這種方式行不通,通過查看JDBC工具類獲取連接的方法我們發現:我們雖然自定義了一個子類,完成了歸還連接的操作。但是DriverManager
獲取的還是JDBC4Connection
這個對象,並不是我們的子類對象。而我們又不能整體去修改驅動包中類的功能!
//將之前的連接對象換成自定義的子類對象
private static MyConnection1 con;
public static Connection getConnection() {
try {
//等效於:MyConnection1 con = new JDBC4Connection(); 子類引用指向父類對象,語法錯誤!
con = DriverManager.getConnection(url,username,password);
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
裝飾設計模式改進連接池
自定義Connection類。通過裝飾設計模式,實現和mysql驅動包中的Connection實現類相同的功能!
實現步驟:
-
定義一個類,實現Connection接口
-
定義Connection連接對象和連接池容器對象的變量
-
提供有參構造方法,接收連接對象和連接池對象,對變量賦值
-
在close()方法中,完成連接的歸還
-
剩余方法,只需要調用mysql驅動包的連接對象完成即可
public class MyConnection2 implements Connection {
//2.定義Connection連接對象和連接池容器對象的變量
private Connection con;
private List<Connection> pool;
//3.提供有參構造方法,接收連接對象和連接池對象,對變量賦值
public MyConnection2(Connection con,List<Connection> pool) {
this.con = con;
this.pool = pool;
}
//4.在close()方法中,完成連接的歸還
@Override
public void close() throws SQLException {
pool.add(con);
}
@Override
public Statement createStatement() throws SQLException {
return con.createStatement();
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return con.prepareStatement(sql);
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return con.prepareCall(sql);
}
@Override
public String nativeSQL(String sql) throws SQLException {
return con.nativeSQL(sql);
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
con.setAutoCommit(autoCommit);
}
@Override
public boolean getAutoCommit() throws SQLException {
return con.getAutoCommit();
}
@Override
public void commit() throws SQLException {
con.commit();
}
@Override
public void rollback() throws SQLException {
con.rollback();
}
@Override
public boolean isClosed() throws SQLException {
return con.isClosed();
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
return con.getMetaData();
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
con.setReadOnly(readOnly);
}
@Override
public boolean isReadOnly() throws SQLException {
return con.isReadOnly();
}
@Override
public void setCatalog(String catalog) throws SQLException {
con.setCatalog(catalog);
}
@Override
public String getCatalog() throws SQLException {
return con.getCatalog();
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
con.setTransactionIsolation(level);
}
@Override
public int getTransactionIsolation() throws SQLException {
return con.getTransactionIsolation();
}
@Override
public SQLWarning getWarnings() throws SQLException {
return con.getWarnings();
}
@Override
public void clearWarnings() throws SQLException {
con.clearWarnings();
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return con.createStatement(resultSetType,resultSetConcurrency);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return con.prepareStatement(sql,resultSetType,resultSetConcurrency);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return con.prepareCall(sql,resultSetType,resultSetConcurrency);
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return con.getTypeMap();
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
con.setTypeMap(map);
}
@Override
public void setHoldability(int holdability) throws SQLException {
con.setHoldability(holdability);
}
@Override
public int getHoldability() throws SQLException {
return con.getHoldability();
}
@Override
public Savepoint setSavepoint() throws SQLException {
return con.setSavepoint();
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return con.setSavepoint(name);
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
con.rollback(savepoint);
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
con.releaseSavepoint(savepoint);
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return con.createStatement(resultSetType,resultSetConcurrency,resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return con.prepareStatement(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return con.prepareCall(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return con.prepareStatement(sql,autoGeneratedKeys);
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return con.prepareStatement(sql,columnIndexes);
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return con.prepareStatement(sql,columnNames);
}
@Override
public Clob createClob() throws SQLException {
return con.createClob();
}
@Override
public Blob createBlob() throws SQLException {
return con.createBlob();
}
@Override
public NClob createNClob() throws SQLException {
return con.createNClob();
}
@Override
public SQLXML createSQLXML() throws SQLException {
return con.createSQLXML();
}
@Override
public boolean isValid(int timeout) throws SQLException {
return con.isValid(timeout);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
con.setClientInfo(name,value);
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
con.setClientInfo(properties);
}
@Override
public String getClientInfo(String name) throws SQLException {
return con.getClientInfo(name);
}
@Override
public Properties getClientInfo() throws SQLException {
return con.getClientInfo();
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return con.createArrayOf(typeName,elements);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return con.createStruct(typeName,attributes);
}
@Override
public void setSchema(String schema) throws SQLException {
con.setSchema(schema);
}
@Override
public String getSchema() throws SQLException {
return con.getSchema();
}
@Override
public void abort(Executor executor) throws SQLException {
con.abort(executor);
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
con.setNetworkTimeout(executor,milliseconds);
}
@Override
public int getNetworkTimeout() throws SQLException {
return con.getNetworkTimeout();
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return con.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return con.isWrapperFor(iface);
}
}
自定義連接池類
public class MyDataSource implements DataSource{
//定義集合容器,用於保存多個數據庫連接對象
private static List<Connection> pool = Collections.synchronizedList(new ArrayList<Connection>());
//靜態代碼塊,生成10個數據庫連接保存到集合中
static {
for (int i = 0; i < 10; i++) {
Connection con = JDBCUtils.getConnection();
pool.add(con);
}
}
//返回連接池的大小
public int getSize() {
return pool.size();
}
//從池中返回一個數據庫連接
@Override
public Connection getConnection() {
if(pool.size() > 0) {
//從池中獲取數據庫連接
Connection con = pool.remove(0);
//通過自定義連接對象進行包裝
MyConnection2 mycon = new MyConnection2(con,pool);
//返回包裝后的連接對象
return mycon;
}else {
throw new RuntimeException("連接數量已用盡");
}
}
}
缺點:Connection
接口中要實現的方法太多了,代碼繁雜
適配器設計模式改進連接池
提供一個適配器類,實現Connection
接口,將所有功能進行實現(除了close()
方法),作為中間類。自定義連接類只需要繼承這個適配器類,重寫需要改進的close()
方法即可!
適配器類不需要實現close()
方法,所以定義為抽象類
public abstract class MyAdapter implements Connection {
// 定義數據庫連接對象的變量
private Connection con;
// 通過構造方法賦值
public MyAdapter(Connection con) {
this.con = con;
}
// 所有的方法,均調用mysql的連接對象實現
@Override
public Statement createStatement() throws SQLException {
return con.createStatement();
}
@Override
public PreparedStatement prepareStatement(String sql) throws SQLException {
return con.prepareStatement(sql);
}
@Override
public CallableStatement prepareCall(String sql) throws SQLException {
return con.prepareCall(sql);
}
@Override
public String nativeSQL(String sql) throws SQLException {
return con.nativeSQL(sql);
}
@Override
public void setAutoCommit(boolean autoCommit) throws SQLException {
con.setAutoCommit(autoCommit);
}
@Override
public boolean getAutoCommit() throws SQLException {
return con.getAutoCommit();
}
@Override
public void commit() throws SQLException {
con.commit();
}
@Override
public void rollback() throws SQLException {
con.rollback();
}
@Override
public boolean isClosed() throws SQLException {
return con.isClosed();
}
@Override
public DatabaseMetaData getMetaData() throws SQLException {
return con.getMetaData();
}
@Override
public void setReadOnly(boolean readOnly) throws SQLException {
con.setReadOnly(readOnly);
}
@Override
public boolean isReadOnly() throws SQLException {
return con.isReadOnly();
}
@Override
public void setCatalog(String catalog) throws SQLException {
con.setCatalog(catalog);
}
@Override
public String getCatalog() throws SQLException {
return con.getCatalog();
}
@Override
public void setTransactionIsolation(int level) throws SQLException {
con.setTransactionIsolation(level);
}
@Override
public int getTransactionIsolation() throws SQLException {
return con.getTransactionIsolation();
}
@Override
public SQLWarning getWarnings() throws SQLException {
return con.getWarnings();
}
@Override
public void clearWarnings() throws SQLException {
con.clearWarnings();
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException {
return con.createStatement(resultSetType,resultSetConcurrency);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return con.prepareStatement(sql,resultSetType,resultSetConcurrency);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException {
return con.prepareCall(sql,resultSetType,resultSetConcurrency);
}
@Override
public Map<String, Class<?>> getTypeMap() throws SQLException {
return con.getTypeMap();
}
@Override
public void setTypeMap(Map<String, Class<?>> map) throws SQLException {
con.setTypeMap(map);
}
@Override
public void setHoldability(int holdability) throws SQLException {
con.setHoldability(holdability);
}
@Override
public int getHoldability() throws SQLException {
return con.getHoldability();
}
@Override
public Savepoint setSavepoint() throws SQLException {
return con.setSavepoint();
}
@Override
public Savepoint setSavepoint(String name) throws SQLException {
return con.setSavepoint(name);
}
@Override
public void rollback(Savepoint savepoint) throws SQLException {
con.rollback(savepoint);
}
@Override
public void releaseSavepoint(Savepoint savepoint) throws SQLException {
con.releaseSavepoint(savepoint);
}
@Override
public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return con.createStatement(resultSetType,resultSetConcurrency,resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return con.prepareStatement(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
}
@Override
public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException {
return con.prepareCall(sql,resultSetType,resultSetConcurrency,resultSetHoldability);
}
@Override
public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException {
return con.prepareStatement(sql,autoGeneratedKeys);
}
@Override
public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException {
return con.prepareStatement(sql,columnIndexes);
}
@Override
public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException {
return con.prepareStatement(sql,columnNames);
}
@Override
public Clob createClob() throws SQLException {
return con.createClob();
}
@Override
public Blob createBlob() throws SQLException {
return con.createBlob();
}
@Override
public NClob createNClob() throws SQLException {
return con.createNClob();
}
@Override
public SQLXML createSQLXML() throws SQLException {
return con.createSQLXML();
}
@Override
public boolean isValid(int timeout) throws SQLException {
return con.isValid(timeout);
}
@Override
public void setClientInfo(String name, String value) throws SQLClientInfoException {
con.setClientInfo(name,value);
}
@Override
public void setClientInfo(Properties properties) throws SQLClientInfoException {
con.setClientInfo(properties);
}
@Override
public String getClientInfo(String name) throws SQLException {
return con.getClientInfo(name);
}
@Override
public Properties getClientInfo() throws SQLException {
return con.getClientInfo();
}
@Override
public Array createArrayOf(String typeName, Object[] elements) throws SQLException {
return con.createArrayOf(typeName,elements);
}
@Override
public Struct createStruct(String typeName, Object[] attributes) throws SQLException {
return con.createStruct(typeName,attributes);
}
@Override
public void setSchema(String schema) throws SQLException {
con.setSchema(schema);
}
@Override
public String getSchema() throws SQLException {
return con.getSchema();
}
@Override
public void abort(Executor executor) throws SQLException {
con.abort(executor);
}
@Override
public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException {
con.setNetworkTimeout(executor,milliseconds);
}
@Override
public int getNetworkTimeout() throws SQLException {
return con.getNetworkTimeout();
}
@Override
public <T> T unwrap(Class<T> iface) throws SQLException {
return con.unwrap(iface);
}
@Override
public boolean isWrapperFor(Class<?> iface) throws SQLException {
return con.isWrapperFor(iface);
}
}
自定義連接類
通過適配器設計模式。完成close()方法的重寫
-
定義一個類,繼承適配器父類
-
定義
Connection
連接對象和連接池容器對象的變量 -
提供有參構造方法,接收連接對象和連接池對象,對變量賦值
-
在
close()
方法中,完成連接的歸還
public class MyConnection3 extends MyAdapter {
//2.定義Connection連接對象和連接池容器對象的變量
private Connection con;
private List<Connection> pool;
//3.提供有參構造方法,接收連接對象和連接池對象,對變量賦值
public MyConnection3(Connection con,List<Connection> pool) {
super(con); // 將接收的數據庫連接對象給適配器父類傳遞
this.con = con;
this.pool = pool;
}
//4.在close()方法中,完成連接的歸還
@Override
public void close() throws SQLException {
pool.add(con);
}
}
自定義連接池類
public class MyDataSource implements DataSource{
//定義集合容器,用於保存多個數據庫連接對象
private static List<Connection> pool = Collections.synchronizedList(new ArrayList<Connection>());
//靜態代碼塊,生成10個數據庫連接保存到集合中
static {
for (int i = 0; i < 10; i++) {
Connection con = JDBCUtils.getConnection();
pool.add(con);
}
}
//返回連接池的大小
public int getSize() {
return pool.size();
}
//從池中返回一個數據庫連接
@Override
public Connection getConnection() {
if(pool.size() > 0) {
//從池中獲取數據庫連接
Connection con = pool.remove(0);
//通過自定義連接對象進行包裝
MyConnection3 mycon = new MyConnection3(con,pool);
//返回包裝后的連接對象
return mycon;
}else {
throw new RuntimeException("連接數量已用盡");
}
}
}
缺點:自定義連接類中的方法已經很簡潔了。剩余所有的方法已經抽取到了適配器類中。但是適配器這個類還是我們自己編寫的,也比較麻煩!所以可以使用動態代理的方式來改進。
動態代理
public class MyDataSource implements DataSource{
//定義集合容器,用於保存多個數據庫連接對象
private static List<Connection> pool = Collections.synchronizedList(new ArrayList<Connection>());
//靜態代碼塊,生成10個數據庫連接保存到集合中
static {
for (int i = 0; i < 10; i++) {
Connection con = JDBCUtils.getConnection();
pool.add(con);
}
}
//返回連接池的大小
public int getSize() {
return pool.size();
}
//動態代理方式
@Override
public Connection getConnection() {
if(pool.size() > 0) {
//從池中獲取數據庫連接
Connection con = pool.remove(0);
Connection proxyCon = (Connection)Proxy.newProxyInstance(con.getClass().getClassLoader(), new Class[]{Connection.class}, new InvocationHandler() {
/*
執行Connection實現類所有方法都會經過invoke
如果是close方法,則將連接還回池中
如果不是,直接執行實現類的原有方法
*/
@Override
public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
if(method.getName().equals("close")) {
pool.add(con);
return null;
}else {
return method.invoke(con,args);
}
}
});
return proxyCon;
}else {
throw new RuntimeException("連接數量已用盡");
}
}
//從池中返回一個數據庫連接
/*@Override
public Connection getConnection() {
if(pool.size() > 0) {
//從池中獲取數據庫連接
Connection con = pool.remove(0);
//通過自定義連接對象進行包裝
//MyConnection2 mycon = new MyConnection2(con,pool);
MyConnection3 mycon = new MyConnection3(con,pool);
//返回包裝后的連接對象
return mycon;
}else {
throw new RuntimeException("連接數量已用盡");
}
}*/
}
開源連接池的使用
C3P0連接池
-
導入jar包
-
導入配置文件到src目錄下
-
創建c3p0連接池對象
-
獲取數據庫連接進行使用
配置文件 c3p0-config.xml
注意該配置文件的名字是固定的不要改,否則無法識別
-
initialPoolSize
:初始化連接數量 -
maxPoolSize
:最大連接數量,當連接數量超過初始化連接數量時,會在連接池內繼續創建連接,直到達到數據庫連接池所能容納的最大連接數量 -
checkoutTimeout
:超過時間。如果使用的連接數量超過最大連接數量,編譯器會在checkoutTimeout
時間以后報錯並終止程序。
<c3p0-config>
<!-- 使用默認的配置讀取連接池對象 -->
<default-config>
<!-- 連接參數 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://主機名:3306/數據庫名</property>
<property name="user">用戶名</property>
<property name="password">密碼</property>
<!-- 連接池參數 -->
<!-- 初始化連接數量 -->
<property name="initialPoolSize">5</property>
<!-- 最大連接數量 -->
<property name="maxPoolSize">10</property>
<!-- 超時時間 -->
<property name="checkoutTimeout">3000</property>
</default-config>
<!-- 創建數據庫連接池時指定名稱-->
<named-config name="otherc3p0">
<!-- 連接參數 -->
<property name="driverClass">com.mysql.jdbc.Driver</property>
<property name="jdbcUrl">jdbc:mysql://主機名:3306/數據庫名</property>
<property name="user">用戶名</property>
<property name="password">密碼</property>
<!-- 連接池參數 -->
<property name="initialPoolSize">5</property>
<property name="maxPoolSize">8</property>
<property name="checkoutTimeout">1000</property>
</named-config>
</c3p0-config>
C3P0數據庫連接池的使用
public static void main(String[] args) throws SQLException {
//創建c3p0連接池對象
DataSource dataSource = new ComboPooledDataSource();
//獲取數據庫連接進行使用
Connection con = dataSource.getConnection();
String s = "select *from emp";
PreparedStatement pst = con.prepareStatement(s);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
String ename = rs.getString("ename");
String job = rs.getString("job");
String hiredate = rs.getString("hiredate");
System.out.println("ename:" + ename + " job:" + job + " hiredate:" + hiredate);
}
rs.close();
pst.close();
con.close(); // 將連接對象歸還池中
}
Druid連接池
-
導入jar包
-
編寫配置文件,放在src目錄下
-
通過Properties集合加載配置文件
-
通過Druid連接池工廠類獲取數據庫連接池對象
-
獲取數據庫連接,進行使用
配置文件druid.properties
driverClassName=com.mysql.jdbc.Driver
url=jdbc:mysql://主機名:3306/數據庫名
username:用戶名
password:密碼
# 初始連接數量
initialSize=5
# 最大連接數量
maxActive=10
# 最長等待時間
maxWait=3000
Druid數據庫的使用
public static void main(String[] args) throws Exception {
//通過Properties集合加載配置文件
InputStream is = demo01.class.getClassLoader().getResourceAsStream("druid.properties");
Properties prop = new Properties();
prop.load(is);
//通過Druid連接池工廠類獲取數據庫連接池對象
DataSource dataSource = DruidDataSourceFactory.createDataSource(prop);
//獲取數據庫連接,進行使用
Connection con = dataSource.getConnection();
PreparedStatement pst = con.prepareStatement("select *from emp");
ResultSet rs = pst.executeQuery();
while (rs.next()) {
String ename = rs.getString("ename");
String job = rs.getString("job");
String hiredate = rs.getString("hiredate");
System.out.println("ename:" + ename + " job:" + job + " hiredate:" + hiredate);
}
rs.close();
pst.close();
con.close();
}
抽取工具類
/*
數據庫連接池工具類
*/
public class DataSourceUtils {
//1.私有構造方法
private DataSourceUtils(){}
//2.定義DataSource數據源變量
private static DataSource dataSource;
//3.提供靜態代碼塊,完成配置文件的加載和獲取連接池對象
static {
try{
//加載配置文件
InputStream is = DruidDemo1.class.getClassLoader().getResourceAsStream("druid.properties");
Properties prop = new Properties();
prop.load(is);
//獲取數據庫連接池對象
dataSource = DruidDataSourceFactory.createDataSource(prop);
} catch(Exception e) {
e.printStackTrace();
}
}
//4.提供獲取數據庫連接的方法
public static Connection getConnection() {
Connection con = null;
try {
con = dataSource.getConnection();
} catch (SQLException e) {
e.printStackTrace();
}
return con;
}
//5.提供獲取數據庫連接池的方法
public static DataSource getDataSource() {
return dataSource;
}
//6.提供釋放資源的方法
public static void close(Connection con, Statement stat, ResultSet rs) {
if(con != null) {
try {
con.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(stat != null) {
try {
stat.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
if(rs != null) {
try {
rs.close();
} catch (SQLException e) {
e.printStackTrace();
}
}
}
public static void close(Connection con, Statement stat) {
close(con,stat,null);
}
}
工具類的使用
public static void main(String[] args) throws SQLException {
//利用工具類獲取DataSoure
DataSource dataSource = DataSourceUtils.getDataSource();
//獲取連接,並使用
Connection con = dataSource.getConnection();
String s = "select *from emp";
PreparedStatement pst = con.prepareStatement(s);
ResultSet rs = pst.executeQuery();
while (rs.next()) {
String ename = rs.getString("ename");
String job = rs.getString("job");
String hiredate = rs.getString("hiredate");
System.out.println("ename:" + ename + " job:" + job + " hiredate:" + hiredate);
}
DataSourceUtils.close(con, pst, rs);
}