1. 相信不少人看這篇文章已經知道鏈接池是用來幹什麼的?沒錯,數據庫鏈接池就是爲數據庫鏈接創建一個「緩衝池」,預先在「緩衝池」中放入必定數量的鏈接欸,當須要創建數據庫鏈接時,從「緩衝池」中取出一個,使用完畢後再放進去。這樣的好處是,能夠避免頻繁的進行數據庫鏈接佔用不少的系統資源。java
2. 常見的數據庫鏈接池有:dbcp,c3p0,阿里的Druid。好了,閒話很少說,本篇文章旨在加深你們對鏈接池的理解。這裏我選用的數據庫是mysql。mysql
3. 先講講鏈接池的流程:sql
首先要有一份配置文件吧!咱們在平常的項目中使用數據源時,須要配置數據庫驅動,數據庫用戶名,數據庫密碼,鏈接。這四個角色萬萬不能夠少。數據庫
相信不少人看這篇文章已經知道鏈接池是用來幹什麼的?沒錯,數據庫鏈接池就是爲數據庫鏈接創建一個「緩衝池」,預先在「緩衝池」中放入必定數量的鏈接欸,當須要創建數據庫鏈接時,從「緩衝池」中取出一個,使用完畢後再放進去。這樣的好處是,能夠避免頻繁的進行數據庫鏈接佔用不少的系統資源。
常見的數據庫鏈接池有:dbcp,c3p0,阿里的Druid。好了,閒話很少說,本篇文章旨在加深你們對鏈接池的理解。這裏我選用的數據庫是mysql。
先講講鏈接池的流程:
首先要有一份配置文件吧!咱們在平常的項目中使用數據源時,須要配置數據庫驅動,數據庫用戶名,數據庫密碼,鏈接。這四個角色萬萬不能夠少。maven
#文件名:db.properties
jdbc.driver=com.mysql.jdbc.Driver
jdbc.url=jdbc:mysql://localhost:3306/ssm
jdbc.username=root
jdbc.password=lfdy
jdbc.initSize=3
jdbc.maxSize=10
#是否啓動檢查
jdbc.health=true
#檢查延遲時間
jdbc.delay=3000
#間隔時間
jdbc.period=3000
jdbc.timeout=100000ide
2. 咱們要根據上述的配置文件db.properties編寫一個類,並加載其屬性學習
public class GPConfig {
private String driver;
private String url;
private String username;
private String password;
private String initSize;
private String maxSize;
private String health;
private String delay;
private String period;
private String timeout;測試
//省略set和get方法//編寫構造器,在構造器中對屬性進行初始化
public GPConfig() {
Properties prop = new Properties();
//maven項目中讀取文件好像只有這中方式
InputStream stream = this.getClass().getResourceAsStream("/resource/db.properties");
try {
prop.load(stream);
//在構造器中調用setter方法,這裏屬性比較多,咱們確定不是一步一步的調用,建議使用反射機制
for(Object obj : prop.keySet()){
//獲取形參,怎麼獲取呢?這不就是配置文件的key去掉,去掉什麼呢?去掉"jdbc."
String fieldName = obj.toString().replace("jdbc.", "");
Field field = this.getClass().getDeclaredField(fieldName);
Method method = this.getClass().getMethod(toUpper(fieldName), field.getType());
method.invoke(this, prop.get(obj));
}
} catch (Exception e) {
e.printStackTrace();
}
}
//讀取配置文件中的key,並把他轉成正確的set方法
public String toUpper(String fieldName){
char[] chars = fieldName.toCharArray();
chars[0] -=32; //如何把一個字符串的首字母變成大寫
return "set"+ new String(chars);
}
}ui
3.好了,咱們配置文件寫好了,加載配置文件的類也寫好了,接下來寫什麼呢?回憶一下,咱們在沒有鏈接池前,是否是用Class.forName(),getConnection等等來鏈接數據庫的?因此,咱們接下來編寫一個類,這個類中有建立鏈接,獲取鏈接的方法。this
public class GPPoolDataSource {
//加載配置類
GPConfig config = new GPConfig();
//寫一個參數,用來標記當前有多少個活躍的鏈接
private AtomicInteger currentActive = new AtomicInteger(0);
//建立一個集合,幹嗎的呢?用來存放鏈接,畢竟咱們剛剛初始化的時候就須要建立initSize個鏈接
//而且,當咱們釋放鏈接的時候,咱們就把鏈接放到這裏面
Vector<Connection> freePools = new Vector<>();
//正在使用的鏈接池
Vector<GPPoolEntry> usePools = new Vector<>();
//構造器中初始化
public GPPoolDataSource(){
init();
}
//初始化方法
public void init(){
try {
//咱們的jdbc是否是每次都要加載呢?確定不是的,只要加載一次就夠了
Class.forName(config.getDriver());
for(int i = 0; i < Integer.valueOf(config.getInitSize());i++){
Connection conn = createConn();
freePools.add(conn);
}
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
check();
}
//建立鏈接
public synchronized Connection createConn(){
Connection conn = null;
try {
conn = DriverManager.getConnection(config.getUrl(), config.getUsername(), config.getPassword());
currentActive.incrementAndGet();
System.out.println("建立一個鏈接, 當前的活躍的鏈接數目爲:"+ currentActive.get()+" 鏈接:"+conn);
} catch (SQLException e) {
e.printStackTrace();
}
return conn;
}
/**
* 建立鏈接有了,是否是也應該獲取鏈接呢?
* @return
*/
public synchronized GPPoolEntry getConn(){
Connection conn = null;
if(!freePools.isEmpty()){
conn = freePools.get(0);
freePools.remove(0);
}else{
if(currentActive.get() < Integer.valueOf(config.getMaxSize())){
conn = createConn();
}else{
try {
System.out.println("鏈接池已經滿了,須要等待...");
wait(1000);
return getConn();
} catch (InterruptedException e) {
e.printStackTrace();
}
}
}
GPPoolEntry poolEntry = new GPPoolEntry(conn, System.currentTimeMillis());
//獲取鏈接幹嗎的?不就是使用的嗎?因此,每獲取一個,就放入正在使用池中
usePools.add(poolEntry);
return poolEntry;
}
/**
* 建立鏈接,獲取鏈接都已經有了,接下來就是該釋放鏈接了
*/
public synchronized void release(Connection conn){
try {
if(!conn.isClosed() && conn != null){
freePools.add(conn);
}
System.out.println("回收了一個鏈接,當前空閒鏈接數爲:"+freePools.size());
} catch (SQLException e) {
e.printStackTrace();
}
}
//定時檢查佔用時間超長的鏈接,並關閉
private void check(){
if(Boolean.valueOf(config.getHealth())){
Worker worker = new Worker();
new java.util.Timer().schedule(worker, Long.valueOf(config.getDelay()), Long.valueOf(config.getPeriod()));
}
}
class Worker extends TimerTask{
@Override
public void run() {
System.out.println("例行檢查...");
for(int i = 0; i < usePools.size();i++){
GPPoolEntry entry = usePools.get(i);
long startTime = entry.getUseStartTime();
long currentTime = System.currentTimeMillis();
if((currentTime-startTime)>Long.valueOf(config.getTimeout())){
Connection conn = entry.getConn();
try {
if(conn != null && !conn.isClosed()){
conn.close();
usePools.remove(i);
currentActive.decrementAndGet();
System.out.println("發現有超時鏈接,強行關閉,當前活動的鏈接數:"+currentActive.get());
}
} catch (SQLException e) {
e.printStackTrace();
}
}
}
}
}
}
4.在上述的check()方法中,要檢查是否超時,因此咱們須要用一個包裝類
public class GPPoolEntry {
private Connection conn;
private long useStartTime;
public Connection getConn() {
return conn;
}
public void setConn(Connection conn) {
this.conn = conn;
}
public long getUseStartTime() {
return useStartTime;
}
public void setUseStartTime(long useStartTime) {
this.useStartTime = useStartTime;
}
public GPPoolEntry(Connection conn, long useStartTime) {
super();
this.conn = conn;
this.useStartTime = useStartTime;
}
}
5.好了,萬事具有,咱們寫一個測試類測試一下吧
public class GPDataSourceTest {
public static void main(String[] args) {
GPPoolDataSource dataSource = new GPPoolDataSource();
Runnable runnable = () -> {
Connection conn = dataSource.getConn().getConn();
System.out.println(conn);
};
ExecutorService executorService = Executors.newFixedThreadPool(5);
for (int i = 0; i < 60; i++) {
executorService.submit(runnable);
}
executorService.shutdown();
}
}
4.好了,我給下個人結果:
5.總結下,這個手寫鏈接池部分,其實我也是學習的別人的,因此有不少東西不熟悉,也有許多漏洞,如今我先說下我須要完善的地方:
反射機制
讀取properties文件
線程池
線程
集合Vector