java自定義連線池
阿新 • • 發佈:2019-01-13
1、java自定義連線池
1.1連線池的概念:
實際開發中"獲取連線"或“釋放資源”是非常消耗系統資源的兩個過程,為了姐姐此類效能問題,通常情況我們採用連線池技術來貢獻連線Connection
用池來管理Connection,這樣可以重複使用Connection,有了池,所以我們就不用自己來建立Connection,而是通過池來獲取Connection物件,當使用完Connection後,呼叫Connection的close()方法也不會真的關閉Connection,而是把Connection“歸還”給池,池也就可以再利用這個Connection物件啦
1.2 自定義連線池需要如下步驟
1.2.1 建立連線池實現(資料來源),並實現介面javax.sql.DataSource.簡化本案案例,我們可以自己提供方法,沒有實現介面
1.2.2 提供一個集合,用於存放連線,因為移除/新增操作過多,所以選用LinkedList較好
1.2.3 為連線池初始化5個連線
1.2.4 程式如果需要連線,呼叫實現類的getConnection(),本方法姜蔥連線池(容器List)獲取連線,為了保證當前連線只是停工給一個執行緒使用,我們需要將連線先從連線池衝移除。
1.2.5 當用戶使用完連線,釋放資源時,不執行close()方法,而是將連線新增到連線池中
程式碼實現:
package com.rookie.bigdata.utils; import java.io.IOException; import java.io.InputStream; import java.sql.Connection; import java.sql.DriverManager; import java.sql.PreparedStatement; import java.sql.ResultSet; import java.sql.SQLException; import java.util.Properties; /** *@author * @date 2019/1/13 */ public class JDBCUtils { private static String driver; private static String url; private static String username; private static String password; /** * 靜態程式碼塊載入配置檔案資訊 */ static { try { // 1.通過當前類獲取類載入器 ClassLoader classLoader = JDBCUtils.class.getClassLoader(); // 2.通過類載入器的方法獲得一個輸入流 InputStream is = classLoader.getResourceAsStream("db.properties"); // 3.建立一個properties物件 Properties props = new Properties(); // 4.載入輸入流 props.load(is); // 5.獲取相關引數的值 driver = props.getProperty("driver"); url = props.getProperty("url"); username = props.getProperty("username"); password = props.getProperty("password"); } catch (IOException e) { e.printStackTrace(); } } /** * 獲取連線方法 * * @return */ public static Connection getConnection() { Connection conn = null; try { Class.forName(driver); conn = DriverManager.getConnection(url, username, password); } catch (Exception e) { e.printStackTrace(); } return conn; } /** * 釋放資源方法 * * @param conn * @param pstmt * @param rs */ public static void release(Connection conn, PreparedStatement pstmt, ResultSet rs) { if (rs != null) { try { rs.close(); } catch (SQLException e) { e.printStackTrace(); } } if (pstmt != null) { try { pstmt.close(); } catch (SQLException e) { e.printStackTrace(); } } if (conn != null) { try { conn.close(); } catch (SQLException e) { e.printStackTrace(); } } } }
package com.rookie.bigdata.datasource; import com.rookie.bigdata.utils.JDBCUtils; import javax.sql.DataSource; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.LinkedList; import java.util.logging.Logger; /** * @author liuxili * @date 2019/1/13 */ public class MyDataSource implements DataSource { //建立一個容器,用於存放connection物件 private static LinkedList<Connection> pool = new LinkedList<>(); //初始化5個連線,放到容器中 static { for (int i = 0; i < 5; i++) { Connection connection = JDBCUtils.getConnection(); pool.add(connection); } } /** * 獲取連線的方法 * * @return * @throws SQLException */ @Override public Connection getConnection() throws SQLException { //當連線池中沒有連線的時候,需要建立連結 if (pool.size() == 0) { for (int i = 0; i < 5; i++) { Connection connection = JDBCUtils.getConnection(); pool.add(connection); } } //從池中獲取連線 return pool.remove(0); } /** * 歸還連線到連線池中 * * @param connection */ public void releaseConnetion(Connection connection) { pool.add(connection); } @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; } }
driver=com.mysql.jdbc.Driver url=jdbc:mysql://localhost:3306/web?useUnicode=true&characterEncoding=utf8 username=root password=root
測試類:
package com.rookie.bigdata.datasource; import org.junit.Test; import java.sql.Connection; import java.sql.PreparedStatement; import java.sql.SQLException; import static org.junit.Assert.*; /** * @author * @date 2019/1/13 */ public class MyDataSourceTest { @Test public void test1() throws SQLException { MyDataSource myDataSource = new MyDataSource(); Connection connection = myDataSource.getConnection(); String sql = "insert into H_USER values(?,?,?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1,1); preparedStatement.setString(2, "張三"); preparedStatement.setInt(3, 23); int rows = preparedStatement.executeUpdate(); System.out.println(rows); myDataSource.releaseConnetion(connection); } }
java自定義連線池改進
實現Connection介面
package com.rookie.bigdata.datasource; import java.sql.*; import java.util.LinkedList; import java.util.Map; import java.util.Properties; import java.util.concurrent.Executor; /** * @author * @date 2019/1/13 */ //實現一個Connection介面 public class MyConnection implements Connection { //定義一個變數 private Connection connection; private LinkedList<Connection> pool; //編寫構造方法 public MyConnection(Connection connection, LinkedList<Connection> pool){ this.connection=connection; this.pool=pool; } @Override public void close() throws SQLException { pool.add(connection); } @Override public PreparedStatement prepareStatement(String sql) throws SQLException { return connection.prepareStatement(sql); } @Override public Statement createStatement() throws SQLException { return null; } @Override public CallableStatement prepareCall(String sql) throws SQLException { return null; } @Override public String nativeSQL(String sql) throws SQLException { return null; } @Override public void setAutoCommit(boolean autoCommit) throws SQLException { } @Override public boolean getAutoCommit() throws SQLException { return false; } @Override public void commit() throws SQLException { } @Override public void rollback() throws SQLException { } @Override public boolean isClosed() throws SQLException { return false; } @Override public DatabaseMetaData getMetaData() throws SQLException { return null; } @Override public void setReadOnly(boolean readOnly) throws SQLException { } @Override public boolean isReadOnly() throws SQLException { return false; } @Override public void setCatalog(String catalog) throws SQLException { } @Override public String getCatalog() throws SQLException { return null; } @Override public void setTransactionIsolation(int level) throws SQLException { } @Override public int getTransactionIsolation() throws SQLException { return 0; } @Override public SQLWarning getWarnings() throws SQLException { return null; } @Override public void clearWarnings() throws SQLException { } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency) throws SQLException { return null; } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return null; } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency) throws SQLException { return null; } @Override public Map<String, Class<?>> getTypeMap() throws SQLException { return null; } @Override public void setTypeMap(Map<String, Class<?>> map) throws SQLException { } @Override public void setHoldability(int holdability) throws SQLException { } @Override public int getHoldability() throws SQLException { return 0; } @Override public Savepoint setSavepoint() throws SQLException { return null; } @Override public Savepoint setSavepoint(String name) throws SQLException { return null; } @Override public void rollback(Savepoint savepoint) throws SQLException { } @Override public void releaseSavepoint(Savepoint savepoint) throws SQLException { } @Override public Statement createStatement(int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null; } @Override public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null; } @Override public CallableStatement prepareCall(String sql, int resultSetType, int resultSetConcurrency, int resultSetHoldability) throws SQLException { return null; } @Override public PreparedStatement prepareStatement(String sql, int autoGeneratedKeys) throws SQLException { return null; } @Override public PreparedStatement prepareStatement(String sql, int[] columnIndexes) throws SQLException { return null; } @Override public PreparedStatement prepareStatement(String sql, String[] columnNames) throws SQLException { return null; } @Override public Clob createClob() throws SQLException { return null; } @Override public Blob createBlob() throws SQLException { return null; } @Override public NClob createNClob() throws SQLException { return null; } @Override public SQLXML createSQLXML() throws SQLException { return null; } @Override public boolean isValid(int timeout) throws SQLException { return false; } @Override public void setClientInfo(String name, String value) throws SQLClientInfoException { } @Override public void setClientInfo(Properties properties) throws SQLClientInfoException { } @Override public String getClientInfo(String name) throws SQLException { return null; } @Override public Properties getClientInfo() throws SQLException { return null; } @Override public Array createArrayOf(String typeName, Object[] elements) throws SQLException { return null; } @Override public Struct createStruct(String typeName, Object[] attributes) throws SQLException { return null; } @Override public void setSchema(String schema) throws SQLException { } @Override public String getSchema() throws SQLException { return null; } @Override public void abort(Executor executor) throws SQLException { } @Override public void setNetworkTimeout(Executor executor, int milliseconds) throws SQLException { } @Override public int getNetworkTimeout() throws SQLException { return 0; } @Override public <T> T unwrap(Class<T> iface) throws SQLException { return null; } @Override public boolean isWrapperFor(Class<?> iface) throws SQLException { return false; } }
package com.rookie.bigdata.datasource; import com.rookie.bigdata.utils.JDBCUtils; import javax.sql.DataSource; import java.io.PrintWriter; import java.sql.Connection; import java.sql.SQLException; import java.sql.SQLFeatureNotSupportedException; import java.util.LinkedList; import java.util.logging.Logger; /** * @author liuxili * @date 2019/1/13 */ public class MyDataSource1 implements DataSource { //建立一個容器,用於存放connection物件 private static LinkedList<Connection> pool = new LinkedList<>(); //初始化5個連線,放到容器中 static { for (int i = 0; i < 5; i++) { Connection connection = JDBCUtils.getConnection(); MyConnection myConnection= new MyConnection(connection,pool); pool.add(myConnection); } } /** * 獲取連線的方法 * * @return * @throws SQLException */ @Override public Connection getConnection() throws SQLException { Connection connection=null; //當連線池中沒有連線的時候,需要建立連結 if (pool.size() == 0) { for (int i = 0; i < 5; i++) { connection = JDBCUtils.getConnection(); MyConnection myConnection= new MyConnection(connection,pool); pool.add(myConnection); } } //從池中獲取連線 return pool.remove(0); } // /** // * 歸還連線到連線池中 // * // * @param connection // */ // public void releaseConnetion(Connection connection) { // pool.add(connection); // // } @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; } }
測試程式碼
@Test public void test2() throws SQLException { MyDataSource1 myDataSource = new MyDataSource1(); Connection connection = myDataSource.getConnection(); String sql = "insert into H_USER values(?,?,?)"; PreparedStatement preparedStatement = connection.prepareStatement(sql); preparedStatement.setInt(1,2); preparedStatement.setString(2, "張三"); preparedStatement.setInt(3, 23); int rows = preparedStatement.executeUpdate(); System.out.println(rows); JDBCUtils.release(connection,preparedStatement,null); }
至此自定義連線池實現完畢,參考黑馬程式設計師視訊教程