關於連接池有不少技術可以用,例如c3p0,druid等等,因為druid有監控平台,性能在同類產品中算top0的。所以我采用的事druid連接池。
首先熟悉一個技術,我們要搞明白,為什么要用他, 他能幫我們解決什么問題?
如果不使用連接池會出現的情況:
a.占用服務器的內存資源
b.導致服務器的速度非常慢
1.准備
下載druid1.9的jar包和對應數據庫的驅動包。
https://mvnrepository.com/artifact/com.alibaba/druid/1.0.9
2.代碼
2.1db.properties
driverClassName=net.sourceforge.jtds.jdbc.Driver url=jdbc:jtds:sqlserver:/XXXXX:1433/szqxjimg;SelectMethod=Cursor;DatabaseName=szqxjimg username=sa password=123456 # 配置參數,讓ConfigFilter解密密碼 #connectionProperties=config.decrypt=true;config.decrypt.key=xxxx # 監控統計攔截的filters filters=stat # 初始化時建立物理連接的個數,初始化發生在顯示調用init方法,或者第一次getConnection時 initialSize=1 # 最大連接池數量 maxActive=10 # 最小連接池數量 minIdle:1 # 獲取連接等待超時的時間,單位毫秒 maxWait=60000 # 配置間隔多久才進行一次檢測,檢測需要關閉的空閑連接,單位是毫秒 # 有兩個含義:1) Destroy線程會檢測連接的間隔時間 2) testWhileIdle的判斷依據,詳細看testWhileIdle屬性的說明 timeBetweenEvictionRunsMillis=60000 # 一個連接在池中最小生存的時間,單位是毫秒 minEvictableIdleTimeMillis=300000 # 用來檢測連接是否有效 validationQuery=SELECT 1 # 申請連接的時候檢測,如果空閑時間大於timeBetweenEvictionRunsMillis,執行validationQuery檢測連接是否有效 testWhileIdle=true # 申請連接時執行validationQuery檢測連接是否有效,做了這個配置會降低性能 testOnBorrow=false # 歸還連接時執行validationQuery檢測連接是否有效,做了這個配置會降低性能 testOnReturn=false # 是否緩存preparedStatement,也就是PSCache poolPreparedStatements=true maxPoolPreparedStatementPerConnectionSize=200
2.2代碼
package com.qihui.qxj.utils; import java.io.InputStream; import java.sql.Connection; import java.sql.ResultSet; import java.sql.SQLException; import java.sql.Statement; import java.util.Properties; import javax.sql.DataSource; import com.alibaba.druid.pool.DruidDataSourceFactory; import com.qihui.qxj.services.system.Brand; public class DruidUtil { private static Properties p; private static DataSource dataSource; static { try { ClassLoader loader = Thread.currentThread().getContextClassLoader(); InputStream inputStream = loader.getResourceAsStream("db.properties"); p = new Properties(); p.load(inputStream); // 通過工廠類獲取DataSource對象 dataSource = DruidDataSourceFactory.createDataSource(p); } catch (Exception e) { e.printStackTrace(); } } public static Connection getConnection() { try { return dataSource.getConnection(); } catch (Exception e) { e.printStackTrace(); } return null; } public static void close(Connection conn, Statement state, ResultSet result) { try { if (result != null) { result.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (conn != null) { conn.close(); } } catch (SQLException e) { e.printStackTrace(); } finally { try { if (state != null) { state.close(); } } catch (SQLException e) { e.printStackTrace(); } } } } public static void main(String[] args) { Brand brand = new Brand(); long startTIme =System.currentTimeMillis(); for (int i = 0; i < 1000; i++) { String selectBrand = brand.getSelectBrand(); } long endTime =System.currentTimeMillis(); System.out.println(endTime- startTIme); } }
3.結論
通過多次測試,發現,循環查詢1000次,不使用連接池,查詢性能為7500ms,使用連接池后,查詢速度為1515ms,可以看出查詢性能優化勒很多。