在企業(yè)級開發(fā)中數(shù)據(jù)庫連接池代碼實現(xiàn),我們往往不會直接使用原生的JDBC操作來實現(xiàn)與數(shù)據(jù)庫得連接。因為數(shù)據(jù)庫的連接是一個很寶貴的資源且耗時,我們往往會在內(nèi)存中引入一個資源池來統(tǒng)一管理數(shù)據(jù)庫的連接。這個模式也被總結(jié)為一種設(shè)計模式:資源池模式和單例模式。 關(guān)于原理部分就不多做介紹了數(shù)據(jù)庫連接池代碼實現(xiàn),這里也是做一個簡單的原理實現(xiàn)。
連接池接口
com.test.pool;
java.util.;
java.util.;
java.util..;
class {
long ;
, ;
() {
= 30000; // 30
= new ();
= new ();
}
T ();
(T o);
void (T o);
T () {
long now = .();
T t;
if (.size() > 0) {
e = .keys();
while (e.()) {
t = e.();
if ((now - .get(t)) > ) {
// has
.(t);
(t);
t = null;
} else {
if ((t)) {
.(t);
.put(t, now);
(t);
} else {
//
.(t);
(t);
t = null;
}
}
}
}
// no , a new one
t = ();
.put(t, now);
(t);
}
void (T t) {
.(t);
.put(t, .());
}
}
連接池實現(xiàn)
com.test.pool;
java.sql.;
java.sql.;
java.sql.;
class {
, url, , ;
() {
}
;
() {
if( == null) {
(.class) {
if( == null) {
= new ();
}
}
}
;
}
@
() {
try {
(.(url, , ));
} catch ( e) {
e.();
(null);
}
}
@
void ( o) {
try {
(() o).close();
} catch ( e) {
e.();
}
}
@
( o) {
try {
(!(() o).());
} catch ( e) {
e.();
(false);
}
}
() {
url;
}
void ( dsn) {
this.url = dsn;
}
() {
;
}
void ( usr) {
this. = usr;
}
() {
;
}
void ( pwd) {
this. = pwd;
}
() {
;
}
void ( ) {
this. = ;
}
void () {
try {
Class.();
} catch (on e) {
}
}
}
Main測試
com.test.pool;
java.sql.;
java.sql.;
class Main {
void main( args[]) {
pool = .();
pool.("com.mysql.jdbc.");
pool.("jdbc:mysql://192.168.2.113:3306/?=false&=true&=UTF-8&=true");
pool.("");
pool.("");
pool.();
// Get a :
con = pool.();
.out.(con.(0));
pool.(con);
}
}
本文由博客一文多發(fā)平臺 發(fā)布!
原文出處: