Written database connection pool (1)

xiaoxiao2021-03-06  99

Recently, I started to develop a website with a powerful background. When using the connection pool, I feel that the connection pool that uses the server to bring some restrictions. At the same time, in order to deepen the learning and research on Java. Write the connection pool class below.

The connection pool mainly has a function;

1) Initialization once, everywhere.

2) Powerful log function records each SQL action, including connection, resultet? And statement

3) According to the number of connections, the connection that has been released or timeout is automatically reclaimed.

4) Configuration is flexible, you can use a variety of JDBC drivers to support multi-driver.

Source code:

/ ** ?? @ Title ?? Connection pool * ?? @Author:? Zxg * ?? @ version?1.0*?@memo: Define database connection and its database connection pool, etc. * /

Package? com.drsl.db;

IMPORT? Java.io. *;

IMPORT? Java.sql. *;

IMPORT? Java.util. *;

IMPORT? Java.util.date;

IMPORT? Java.lang.reflect. *;

IMPORT? com.mysql.jdbc.driver;

Import? com.drsl.db. *;

PUBLIC?

Class? ConnectionManager? {

????

????

Static?

PRIVATE? CONNECTIONMANAGER? Instance;? INSTANCE;?

//? Single instance

????

Static?

PRIVATE?

Int? clients;

????

Static?

PRIVATE?

INT? MAXONLINETIME = 30 * 60 * 1000;

????

????

PRIVATE? Vector? drivers? =?

NEW? Vector ();

????

PRIVATE? HashTable? Pools? =?

NEW? hashtable ();

????

PRIVATE? TIMER? CheckConNTIMER =

NEW? TIMER ();

????

????

Static?

PRIVATE? PRINTWRITER? LOG;

????

/ ** ???? *? Return the only instance. If this method is called for the first time, create an instance ???? * ???? *? @ RETURN? ConnectionManager? Unique instance ???? * /

????

Static?

SYNCHRONIZED?

PUBLIC? ConnectionManager? GetInstance ()? {

????????

IF? (instance? ==? null)? {

???????????? INSTANCE? =?

NEW? connectionManager ();

????????}

// ???????? Clients ;

????????

RETURN? Instance;

????}

????

????

/ ** ???? *? Constructing a function private to prevent other objects from creating this type of instance ???? * /

????

PRIVATE? ConnectionManager ()? {

???????? init ();

????}

????

????

/ ** ???? *? Read attribute completes initialization ???? * /

????

PRIVATE?

void? init ()? {

????????

????????

Try? {

????????????

???????????? INPUTSTREAM ???? is? = ?? getClass (). GetResourceAsStream (

"db.properties");

????????????

???????????? properties ???? dbprops? =? New? Property ();

????????

???????????? dbprops.Load (IS);

????????}

????????

Catch? (Exception? e)? {

???????????? E.PrintStackTrace ();

???????????? system.err.println (

"Can you read the property file =?"?

????????????

"Please make sure DB.Properties in the path specified by classpath");

????????????

Return;

????????}

???????? String? Logfile? =? Dbprops.getproperty (

"logfile",?

"log.txt");

????????

Try? {

???????????? log? =?

NEW? PrintWriter

NEW? FileWriter (logfile ,?

True),?

True);

????????}

????????

Catch? (IOEXCEPTION? E)? {

???????????? system.err.println (

"Unable to open the log file:?"? ? Logfile;

???????????? log? =?

NEW? PrintWriter (System.err);

????????}

???????? loadDrivers (dbprops);

???????? CreatePools (dbprops);

????}

????

????

/ ** ???? *? Loading and register all JDBC drivers ???? * ???? *? @ Param? PrOPS? Property ???? * /

????

PRIVATE?

Void? LoadDrivers (Properties? PROPS)? {

???????? String? Driverclasses? =? PrOPs.getProperty

"drivers");

???????? STRINGTOKENIZER? ST? =?

NEW? STRINGTOKENIZER (driverclasses);

????????

While? (st.hasmorelements ())? {

???????????? String? Driverclassname? =? St.nextToken (). Trim ();

????????????

Try? {

????????????????

??????????????????????????????????????????????????????????????????????????????????? (driverclassname) .newInstance ();

????????????????

IF (driver! = null) {

???????????????????? drivermanager.registerDriver;

???????????????????? driver.addelement (driver);

???????????????????? log (

"Begin");

???????????????????? log (

"Successfully registered JDBC driver"? ? Driverclassname;

?????????????????}

????????????????

Else {

???????????????????? log (

"Begin");

???????????????????? log (

"Register JDBC Driver"? ? DriverclassName

"failure");

?????????????????} ????????????????????

????????????}

????????????

Catch? (Exception? e)? {

???????????????? log (

"Begin");

???????????????? log (

"Unable to register the JDBC driver:?"? Driverclassname? ?

", Error:?" ? E);

????????????}

????????}

????}

????

????

/ ** ???? *? Create a connection pool instance according to the specified attribute. ???? * ???? *? @ Param? Version? Connection pool property ???? * /

????

PRIVATE?

Void? creagepools (property? pROPS)? {

????????

???????? enumeration? PROPNAMES? =? PROPS.PROPERTYNAMES ();

????????

While? (PROPNAMES.HASMOREELEMENTS ())? {

???????????? String? Name? =? (String)? PropNames.nexTelement ();

????????????

IF? (name.endswith)

".url"))? {

???????????????? String? Poolname? =? Name.substring (0,? Name.lastindexof

"."));

???????????????? String? URL? =? PROPS.GETPROPERTY (POOLNAME? ?

".url");

????????????????

IF? (URL? ==? null)? {

???????????????????? log (

"No pool"? ? Poolname? ?

"Specify URL");

????????????????????

CONTINUE;

?????????????????}

????????????????

???????????????? String? User? =? PrOPs.getProperty (poolname? ?

".user");

???????????????? String? Password? =? PROPS.GETPROPERTY (POOLNAME? ?

".password");

????????????????

???????????????? String? MaxConn? =? PrOPs.getProperty (PoolName? ?

".maxconn",?

"0");

???????????????? String? MinConn? =? PROPS.GETPROPERTY (POOLNAME? ?

".minconn",?

"10");

???????????????? String? Option = props.getProperty (PoolName

".option",

"" "

????????????????

Int? max, min;

????????????????

Try? {

???????????????????? MAX? =? integer.Valueof (MaxConn) .intValue ();

????????????????????

?????????????????}

????????????????

Catch? (NUMBERFORMATEXCETION? E)? {???????????? log (

"The wrong maximum connection limit:?"? ? MaxConn? ?

"? Connect pool:?"? ? Poolname;

???????????????????? max? =? 0;

?????????????????}

????????????????

????????????????

Try? {

??????????????????????????????????????????????????????????????????????????????????????????? integer.valueof

????????????????????

?????????????????}

????????????????

Catch? (NUMBERFORMATEXCETION? E)? {

???????????????????? log (

"The wrong minimum connection limit:?"? ? Minconn? ?

"? Connect pool:?"? ? Poolname;

???????????????????????????????????

?????????????????}

????????????????

????????????????

Try {

???????????????????? connectionpool? Pool? =?

NEW? ConnectionPool (PoolName, URL, User, Password, MIN, MAX, OPTION);

????????????????????

???????????????????? pools.put (PoolName,? pool);

????????????????????

????????????????????

// 2 seconds, start each minute to check the connection pool

???????????????????? CHECKCONNTIMER.SCHEDULE (POOL, 2000, 60 * 1000);

???????????????????? log (

"Create a connection pool"? ? Poolname);

????????????????????

?????????????????}

Catch (Exception? E) {

???????????????????? log (e,

"Create DBConnectionPool error");

?????????????????}

????????????}

????????}

????}

????

/ ** ???? *? Return the connection object to the connection pool specified by the name * ????? *? @ Param? Name? In the properties file name ???? * ? @Param? Con connection object ???? * /

????

PUBLIC?

Void? FREECONNECTION (STRING? NAME,? Connection? conn)? {

???????? connectionpool? Pool? =? (Connectionpool)? Pools.get (name);

????????

IF? (pool?! =? null)? {

???????????? pool.freeConnection (conn);

????????}

????}

????

????

/ ** ???? *? Get a available (idle) connection. If there is no connection available, and the number of connections is less than the maximum connection number ???? *? Limit, create and return new connection ??? ? * ???? *? @ param? Name? The connection pool name defined in the properties file ???? *? @ RETURN? Connection? Available connection or null ???? * /

????

PUBLIC? Connection? getConnection (String? Name)? {

???????? connectionpool? Pool? =? (Connectionpool)? Pools.get (name); ????????

IF? (pool?! =? null)? {

????????????

RETURN? POOL.GETCONNECTION ();

????????}

????????

Return? NULL;

????}

????

????

/ ** ???? *? Get a available connection. If there is no connection available, and the number of connections is less than the maximum connection limit, the new connection is created and returned. Otherwise, within the specified time Waiting for other threads to release the connection. ???? * ????? *? @ Param? Name? Connect pool name ???? *? @ Param? Time? Take the waiting time for milliseconds ???? @ Return ? Connection? Available connection or null ???? * /

????

PUBLIC? Connection? getConnection (String? Name ,?

Long? Time)? {

???????? connectionpool? Pool? =? (Connectionpool)? Pools.get (name);

????????

IF? (pool?! =? null)? {

????????????

RETURN? POOL.GetConnection (TIME);

????????}

????????

Return? NULL;

????}

????

????

/ ** ???? *? Close all connections, revoke the registration of the driver ???? * /

????

PUBLIC?

SYNCHRONIZED?

Void? release ()? {

????

//? Waiting until the last customer is called

// ???????? IF? (- clients?! =? 0)? {

// ???????????? Return;

// ????????}

????????

???????? checkconntimer.cancel ();

????????

???????? enumeration? Allpools? =? Pools.efficient ();

????????

While? (allPools.hasmoreElements ())? {

???????????? connectionpool? Pool? =? (ConnectionPool)? Allpools.nexTelement ();

???????????? pool.cancel ();

???????????? pool.release ();

????????}

???????? enumeration? Alldrivers? =? Drivers.ements ();

????????

While? (alldrivers.hasmorelements ())? {

???????????? driver? Driver? =? (Driver) alldrivers.nextelement ();

????????????

Try? {

???????????????? drivermanager.deregisterDriver (driver);

???????????????? log (

"Undo JDBC driver?"? ? Driver.getClass (). Getname ()

"Register");

????????????}

????????????

Catch? (SQLEXCEPTION? E)? {

???????????????? log (e,

"Registration of the following JDBC driver unable to revoke:?"? Driver.getClass (). Getname ());

????????????}

????????}

????}

????

????

/ ** ???? *? Write text information to log files ???? * /

????

Static?

PUBLIC?

Void? log (String? msg)? {???????? log.println

New? Date ()? ?

":?" ? msg;

????}

????

????

/ ** ???? *? Write text information with exceptions to log files ???? * /

????

Static?

PUBLIC?

Void? log (throwable? e,? String? msg)? {

???????? log.println

New? Date ()? ?

":?" ? msg;

???????? E.PrintStackTrace (log);

????}

//test

????????

????

Static?

PUBLIC?

Void? main (string []? args? {

????????

???????? ????????

????????

????????

Try {

????????????? dcm = connectionManager.getInstance ();

????????????

???????????? connection? Conn = dcm.getConnection

"mysql");

???????????? connection? Conn1 = dcm.getConnection

"mysql");

???????????? connection? Conn2 = dcm.getConnection

"mysql");

???????????? connection? Conn3 = dcm.getConnection

"mysql");

???????????? connection? Conn4 = dcm.getConnection

"mysql");

???????????? connection? Conn5 = DCM.GetConnection

"mysql");

???????????? connection? Conn6 = dcm.getConnection

"mysql");

???????????? connection? Conn7 = dcm.getConnection

"mysql");

???????????? connection? Conn8 = DCM.GetConnection

"mysql");

???????????? connection? Conn9 = dcm.getConnection

"mysql");

???????????? connection? Conn10 = dcm.getConnection

"mysql");

???????????? connection? Conn11 = dcm.getConnection

"mysql");

???????????????????????????????????????? connection? Conn12 = dcm.getConnection

"mysql");

???????????? connection? Conn13 = dcm.getConnection

"mysql");

?????????????????????????????????? connection? Conn14 = dcm.getConnection

"mysql");

????????????

???????????? resultet? Rs;

????????????

???????????? String? SQL =

"SELECT? *? from? CSS";

????????

???????????? statement? ST = conn.createstatement (); ????????????

IF (ST == NULL)? {

???????????????? log (

"Main - Error? While? Get? /" statement / "");

????????????????

Return;

????????????}

???????????? rs = st.executeQuery (SQL);

????????????

IF (rs == null) {

???????????????? log (

"Main - Error? While? Get? /" resultset / "");

????????????????

Return;

????????????}

???????????? system.out.println

"/ r / n");

?????????????????????????

????????????

While (rs.next ()) {

???????????????? system.out.println (rs.getstring (1));

????????????}

???????????? rs.close ();

???????????? st.close ();

???????????? rs = NULL;

???????????? ST = NULL;

????????????

????????????

???????????? conn.close ();

???????????? conn1.close ();

???????????? conn2.close ();

???????????? conn3.close ();

???????????? conn4.close ();

???????????? conn5.close ();

???????????? conn6.close ();

???????????? conn7.close ();

???????????? conn8.close ();

???????????? conn9.close ();

???????????? conn10.close ();

???????????? conn11.close ();

???????????? conn12.close ();

???????????? conn13.close ();

???????????? conn14.close ();

????????????

???????????? conn = NULL;

???????????? conn1 = NULL;

???????????? conn2 = NULL;

???????????? conn3 = NULL;

???????????? conn4 = NULL;

???????????? conn5 = NULL;

???????????? conn6 = NULL;

???????????? conn7 = NULL;

???????????? conn8 = NULL;

???????????? conn9 = NULL;

???????????? conn10 = NULL;

???????????? conn11 = NULL;

???????????? conn12 = NULL;

???????????? conn13 = NULL;

???????????? conn14 = NULL;

????????????

????????}

Catch (SQLEXCEPTION? E) {

???????????? dcm.log (e,

"main - error");

????????}

????}

}

//

/ ************** Contact pool class *************************************** ***************** * ***? This class defines a connection pool. It can create a new connection as required until the predetermined most * Dalian Digital Before returning to the client, it can verify the validity of the connection. *? It inherits it from? Timertask? Timer member scheduling of the CONNECTIONMANAGER? Class * /

Package? com.drsl.db;

IMPORT? Java.io. *;

IMPORT? Java.sql. *;

IMPORT? Java.util. *;

IMPORT? Java.util.date;

IMPORT? Java.lang.reflect. *;

Import? com.drsl.db. *;

PUBLIC?

Class? ConnectionPool?

EXTENDS? TIMERTASK {

????

????

PRIVATE?

Int? countconn;

????

????

PRIVATE? VECTOR? FREECONNS? =?

NEW? Vector ();

????

PRIVATE? Vector? usingconns? =?

NEW? Vector ();

????

????

PRIVATE?

Int? MaxUsetime;

// The maximum idle time in use

????

PRIVATE?

Int? maxfreetime;

// Turn off this connection when the maximum idle time (when the number is not less than the minimum connection)

????

????

PRIVATE?

Int? maxconn;

// maximum connection number

????

PRIVATE?

Int? minconn;

// minimum connection number

????

????

PRIVATE? STRING? NAME;

// pool? name

????

PRIVATE? STRING? URL;

????

PRIVATE? STRING? User;

????

PRIVATE? STRING? Password;

????

PRIVATE? STRING? Option;

????

// ???? private ?printwriter? log;

????

/ ** ???? *? Create a new connection pool ???? * ???? *? @ Param? Name? Connect pool name ???? *? @ Param? URL? Database JDBC? URL? ??? *? @ param? DBINFO? Database connection information ???? *? @ param? MaxConn? This connection pool allows the maximum number of connections to be established ???? * /

????

PUBLIC? ConnectionPool (String? Name,? String? URL, STRING? User, string? password,?

Int? MinConn,

INT? MaxConn, String? Option? {

????????

THIS.NAME =? Name;

????????

this.url? =? URL;

????????

THIS.USER? =? user;

????????

THIS.PASSWORD? =? password;

????????

THIS.OPTION = Option;

????????

????????

THIS.MAXCONN? =? maxconn;

????????

THIS.MINCONN? =? minconn;

????????

????????

IF

THIS.MINCONN <= 0)?

THIS.MINCONN = 10;

????????

???????? log (

"END? One? Part / R / N");

????????

FOR

INT? I = 0;? i

???????????? newConnection ();?

????????}

????}

????

/ ** ???? *? Add a new connection to the connection pool ???? * ???? *? @ Param? Connobj? New connection ???? * / ????

PUBLIC?

SYNCHRONIZED?

Void? FREECONNECTION (ConnectionObject? connobj)? {

????????

/ /? Add the specified connection to the end of the vector

????????

Try {

???????????? connobj.setinuse (

FALSE);

???????????? FREECONNS.Addelement (connobj);

???????????? log (

"Successfully record a new connection or reclaim a release connection");

???????????? notifyAll ();

????????}

Catch (arrayindexoutofboundsexception? e) {

???????????? log (e,

"FREECONNECTION (ConnectionObject? connobj)? - failed");

????????????

????????}

????}

????

/ ** ???? *? Back to the connection pool to the connection pool ???? * ????? *? @ Param? Conn? Customer proactive release connection ???? * /

????

PUBLIC?

SYNCHRONIZED?

Void? FREECONNECTION (Connection? conn)? {

????????

/ /? Add the specified connection to the end of the vector

???????? connECTIONOBJECT? Connobj = null;

????????

????????

FOR

INT? i = 0; i

???????? {

???????????? connobj = (connectionObject) USINGCONNS.GET (i);

????????????

????????????

IF (connobj.getConnection () == conn)

????????????????

Break;

????????}

????????

IF (connobj! = null) {

????????????

Try {

????????????????? connobj.setinuse (

FALSE);

???????????????? FREECONNS.ADDELEMENT (CONNOBJ);

???????????????? USINGCONNS.RemoveElement (connobj);

???????????????? log (

"Successful recycling");

???????????????? NOTIFYAll ();

????????????}

Catch (Exception? E) {

???????????????? log (e,

"Recycling a connection - failed");

????????????}

????????}

????}

????

????

/ ** ???? *? A available connection is obtained from the connection pool. If there is no idle connection and the current connection is less than the maximum connection ???? *? Number limit, create a new connection. If you have been registered as available connection No longer valid, then delete from the vector, ???? *? Then recursively call yourself to try new available connections. ???? * /

????

PUBLIC?

SYNCHRONIZED? Connection? getConnection ()? {

???????? connECTIONOBJECT? CONNOBJ? =? NULL;

???????? connection? Conn = NULL;

????????

/ /? Get the first available connection in the vector

????????

Try? {

???????????? connobj? =? (ConnectionObject)? freeconns.get (0);

????????}

????????

Catch? (Exception? E)? {????????????

???????????? log (

"END? One? Part / R / N");

???????????? log (

"From the connection pool"? ? Name

"Get a connection failed");

????????????

IF (? MaxConn? ==? 0? ||? Countconn?

???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????? NewConnection ();

????????????}

????????}

????????

// Create a new connection if there is no idle connection and the current connection is less than the maximum connection limit.

????????

IF (connobj == null? &&? (? MaxConn? ==? 0? ||? countryconn?

???????????? log (

"From the connection pool"? ? Name

"Get a connection failed");

???????????? log (

"END? One? Part / R / N");

???????????? connobj? =? newConnection ();

????????}

????????

IF? (connobj?! =? null)? {

????????????

???????????? connobj.setlastaccesstime

NEW? DATE (). getTime ());

???????????? connobj.setinuse (

True);

????????????

???????????? usingConns.addelement (connobj);

???????????? FREECONNS.RemoveElementat (0);

????????????

???????????? conn = connobj.getConnection ();

????????????

RETURN? conn;

????????????

????????}

Else {

???????????? log (

"Get connection"? ? Name

"Failure - the number of connections has reached the maximum upper limit");

????????????

Return? NULL;

????????}

????}

????

????

/ ** ???? *? Access available connections from the connection pool. You can specify the maximum time for the client to wait for the longest time ???? *? See the previous getConnection () method. ???? * ???? * ? @Param? Timeout? Waiting time limit in milliseconds ???? * /

????

PUBLIC?

SYNCHRONIZED? Connection? getConnection

Long? Timeout? {

????????

????????

Long? StartTime? =?

New? Date (). gettime ();

???????? connection? Conn = NULL;

????????

While? (conn? =? getConnection ())? ==? null)? {

????????????

Try? {

???????????????????????????????????????????????????????????????????????????????????????????

// ??????????????????????????????????????????

????????????}

????????????

Catch? (InterruiptedException? E) {

????????????????

????????????}

????????????

IF?

New? Date (). getTime ()? -? STARTTIME)?> =? Timeout? {

????????????????

//? Wait () The reason is that timeout ?????????

???????????????? RETURN? NULL;

????????????}

????????}

????????

RETURN? conn;

????}

????

????

/ ** ???? *? Close all connections ???? * /

????

PUBLIC?

SYNCHRONIZED?

Void? release ()? {

// ???????? ca Zancel ();

???????? enumeration? AllConnections? =? Freeconns.efficient ();

????????

????????

While? (AllConnections.hasMoreElements ())? {

???????????? connectionObject? Connobj? =? (ConnectionObject)? AllConnections.nexTelement ();

????????????

Try? {

????????????????????????? connobj.close ();

???????????????? connobj = null;

???????????????? log (

"Close connection pool"? ? Name

"One connection");

????????????}

????????????

Catch? (SQLEXCEPTION? E)? {

// sqlexception

???????????????? log (e ,?

"Unable to turn off the pool"? ? Name

"Connection");

????????????}

????????}

???????? FREECONNS.RemoveAllelements ();

????????

//

???????? allConnections? =? usingConns.efficient ();

????????

????????

While? (AllConnections.hasMoreElements ())? {

???????????? connectionObject? Connobj? =? (ConnectionObject)? AllConnections.nexTelement ();

????????????

Try? {

????????????????????????? connobj.close ();

???????????????? connobj = null;

???????????????? log (

"Close connection pool"? ? Name

"One connection");

????????????}

????????????

Catch? (SQLEXCEPTION? E)? {

// sqlexception

???????????????? log (e ,?

"Unable to turn off the pool"? ? Name

"Connection");

????????????}

????????}

???????? usingconns.removeallelements ();

????}

????

????

/ ** ???? *? Create a new connection ???? * /

????

PRIVATE? CONNECTIONOBJECT? NewConnection ()? {

???????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????

????????

Try? {

????????????

???????????? log (

"Connecting pool"? ? Name

"Create a new connection object");

?????????????

???????????? String? Url = url option;

????????????

????????????? log (

"URL ="? URL?); ?????????????

????????????? connection? Conn? =? Drivermanager.getConnection (URL, User, Password);

????????????

???????????? connobj =

NEW? ConnectionObject (conn,

FALSE);

????????????

???????????? FREECONNECTION (CONNOBJ);

???????????? countConn ;

????????????

????????}?

????????

Catch? (SQLEXCEPTION? E)? {?

???????????? log (e ,?

"Unable to create the following URL connection:?"? ? URL

"? for? user =?"? user

"? Password =" password);?

????????????

Return? null;?

????????}?

????????

RETURN? Connobj;?

????}?

????

/ / Check each connection status (once every minute)

????

PUBLIC?

Void? run? () {

????????

???????? connECTIONOBJECT? Connobj = null;

????????

// Recycling? Is it "closed" connection ????

????????

/ / And? Use time has been connected

????????

INT? i = 0; ????

????????

While (i

????????????? connobj = (connectionObject) UsingConns.get (i);

????????????

IF (connobj.isinuse () ==

False) {

????????????????

Try {

???????????????????????? log (

"RUN - Recycling? The already /" closed / "connection");?

????????????????freeConnection (connobj);

???????????????????????? usingConns.removeElementat (i); ????????

????????????????????????? I -;

?????????????????}

Catch (arrayindexoutofboundsexception? e) {

???????????????????? log (e,

"RUN - Recycling? It is already using /" Off / "Connection - Failure");?

?????????????????}

????????????}

Else {

????????????

????????????????

Long? NOWTIME =

New? Date (). gettime ();

????????????????

Long? t = nowtime-connobj.getlastaccesstime ();

????????????????

Try {

????????????????????

IF (T> 20 * 60 * 1000) {

// Timeout is 20 minutes

???????????????????????? log (

"RUN - Recycling? Use the timeout timeout");?

????????????????freeConnection (connobj);

???????????????????????? USINGCONNS.RemoveElementat (I);

??????????????????????????i-; ????????????????????}

?????????????????}

Catch (arrayindexoutofboundsexception? E?) {

???????????????????? log (e,

"RUN - Recycling? Connection for time delivery - failed");?

?????????????????}

????????????}

???????????? i ;

????????}

????????

/ / Delete? Idle has been connected to the connection

???????? i = 0;

????????

While (i

????????

???????????? connobj =? (connectionObject) freeConns.get (i);

????????????

Try {

????????????????

IF (connobj.getConnection (). isclosed ()) {

???????????????????? connobj = NULL;

???????????????????? FREECONNS.RemoveElelementat (I);

???????????????????? countconn

???????????????????? I -;

???????????????????? log (

"RUN - delete? Idle has been unexpectedly closed");?

?????????????????}

????????????}

Catch (Exception? E) {

???????????????? log (e,

"RUN - delete? Idle has been unexpectedly closed connection - failed");?

????????????}

???????????? i ;

????????}

????????

????????

/ / Delete? Is it redundant from an idle connection (larger than the minimum number of connections)?

????????

Long? cc = countconn-minconn;

???????? i = 0;

????????

While (i

1){

????????????

Try {

???????????????? connobj = (connectionObject) FREECONNS.GET (0);

????????????????????????? connobj.close ();

???????????????? connobj = null;

????????????????freeconns.removeelementat (0);

???????????????? countconn

???????????????? log (

"RUN - delete? From the idle connection (greater than the minimum number of connections) connections?");?

????????????}

Catch (SQLEXCEPTION? E) {

???????????????? log (e,

"RUN - from the idle connection (larger than the minimum connection) connection - failed");?

????????????}

???????????? i ;

????????}

????????

/ / Add connection? Maintain the minimum number of connections required

????????

IF (CC <0) {

???????????? cc = -CC;

???????????? log (

"END? One? Part / R / N");

???????????? log (

"RUN - increase the connection? Maintain the minimum number of connections required");?

????????????

For (i = 0; i

???????????????? newConnection ();

????????????}

????????}

????????

/ / Add connection? Keep at least one available connection

????????

IF (freeConns.size () <1) {???????????? log (

"END? One? Part / R / N");

???????????? log (

"RUN - increase connection? Keep at least one available connection");?

???????????? newConnection ();

????????}

???????? log (

"Run - OnCE");

????

// ???? notifyAll ();

????}

????

/ ** ???? *? Write text information to log files ???? * /

????

PRIVATE?

Void? log (String? msg)? {

???????? connectionManager.log (msg);

????}

????

????

/ ** ???? *? Write text information with exceptions to log files ???? * /

????

PRIVATE?

Void? log (throwable? e,? String? msg)? {

???????? ConnectionManager.log (e, msg);

????}

????????

}

/

/ **? *? Data connection self-encapsulation, blocking the close method and the CreateStatement, the PrepareStatement? Method to return your own takeover class? *? @ Author? Zxg? * /

Package? com.drsl.db;

IMPORT? Java.io. *;

IMPORT? Java.sql. *;

IMPORT? Java.util. *;

IMPORT? Java.util.date;

IMPORT? Java.lang.reflect. *;

PUBLIC?

Class? ConnectionObject?

IMPLEMENTS? INVOCATIONHANDLER {

????

????

PRIVATE?

Final?

Static? String? Close_method_name? =?

"close";

????

PRIVATE?

Final?

Static? String? CREATSTATION_METHOD_NAME? =?

"createstatement";

????

PRIVATE?

Final?

Static? String? pre previousatement_method_name? =?

"preordate";

????

????

PRIVATE? Connection? conn? =? NULL;

????

PRIVATE ???? connection? conn_proxy = NULL;

????

PRIVATE? PREPAREDSTATEMENTOBJECT? PSO = NULL;

????

PRIVATE? STATEMENTOBJECT? STMO = NULL;

????

????

// Database busy state

????

PRIVATE?

Boolean? Inuse? =?

False;

????

????

// The user's last time access to the connection method

????

PRIVATE?

Static?

Long? LastAccesstime? =?

New? Date (). gettime ();

????

PUBLIC? ConnectionObject (connection? conn ,?

Boolean? inuse) {

????????

THIS.CONN? =? conn;

????????

this.inuse? =? inuse;

????}

????

????

/ **???????Returns?the?conn.?????*?@return?connection ?????

????

/ / Return to the database connection CONN's takeover class to intercept each method ????

PUBLIC? Connection? getConnection ()? {

????????

IF (conn_proxy == null) {

???????????? ClassLoader? Classloader = conn.getClass (). GetClassLoader ();

???????????? class []? Interfaces? =? Conn.getClass (). GetInterfaces ();?

????????????

????????????

IF (interfaces == null || interfaces.length == 0) {?

???????????????? interfaces? =?

NEW? Class [1];?

????????????????????????? INTERFACES [0]? =? connection.

Class;?

????????????}

????????????

????????????

Try {

????????????????

???????????????? conn_proxy =? (Connection) proxy.newproxyinstance (ClassLoader, Interfaces,

THIS);

????????????????

????????????}

Catch (NULLPOINTEREXCEPTION? E) {

???????????????? log (e,

"ConnectionObject? GetConnection () - Error");

????????????}

????????????

IF (conn_proxy! = null)

???????????????? log (

"ConnectionObject? GetConnection () - Success");

????????}

????????

RETURN? conn_proxy;

????}

????

????

/ ** ????? *? This method really turns off the connection of the database ????? *? @ THROWS? SQLEXCEPTION ????? * /

????

SYNCHRONIZED?

Void ?? close ()?

THROWS? SQLEXCEPTION {

????????

// Since the class attribute conn is not connected to the connection, once the Close method is called, the connection is turned directly.

???????? conn.close ();

???????? conn = NULL;

????}

????

/**???????Returns?the?inuse.?????*?@return?boolean?????/

????

PUBLIC?

Boolean? Isinuse ()? {

????????

RETURN? inuse;

????}

????

/ ** ????? *? @ See? java.lang.reflect.invocationHandler # INVOKE (java.lang.Object,? java.lang.reflect.Method,? java.lang.object) ????? * /

????

PUBLIC? Object? Invoke (Object? PROXY,? METHOD? M,? Object []? args?

????????

THROWS? THROWABLE?

???? {

???????? Object? Obj? =? Null;

???????? log (

"ConnectionObject - Invoke: METHOD:? /" M.GetName ()

"/" ");

????????

????????

/ / Judgment whether the method is called, if the CLOSE method is called, the connection is used to useless.

????????

????????

IF (close_method_name.equals (m.getname ())) {

???????????? setinuse (

FALSE);

????????????????????

????????}

Else?

IF (creatstatment_method_name.equals (m.getname ())) {

????????????

????????

/ / If you call? CreateStatment? Method, package? STATEMENT? Accept management

????????

???????????? statement? STM = (statement)? M.invoke (conn,? Args);

????????????

IF (STM! = NULL? &&? STMO == NULL) {

???????????????? STMO =

NEW? STATEMENTOBJECT (STM);

???????????????? obj = stmo.getStatement ();

????????????}

Else {

???????????????? connectionmanager.log

"ConnectionObject - Invoke: METHOD:? /" M.GetName ()

"/"--failure");

????????????}

????????????

????????}

Else?

IF (preplestatement_method_name.equals (m.getname ()))) {

????????????

????????

/ / If you call? CreateStatment? How to encapsulate? PREPAREDSTATEMENT? Accept management

????????

???????????? preparedStatement? Ps = (preparedStatement)? M.Invoke (conn,? Args);

????????????

????????????

IF (PS! = NULL? &&? pso == null) {

???????????????? pso =

NEW? PreparedStatementObject (PS);

????????????}

????????????

Else?

IF (PSO! = null) {

???????????????? obj = pso.getpreparedStatement ();

????????????}

Else

???????????????? log (

"ConnectionObject - Invoke: METHOD:? /" M.GetName ()

"/"--failure");

????????????

????????}

Else

???????????? Obj? =? M.Invoke (conn,? args); ????

????????????

????????

/ / Set the last access time to clear the timeout connection in time

???????? lastaccesstime? =?

New? Date (). gettime ();

????????

Return? OBJ;

????}

????????

????

/**???????Returns?the?lastaccesstime. ?????*@return?long?????

????

PUBLIC?

Static?

Long? getlastaccesstime ()? {

????????

RETURN? LastAccesstime; ????}

????

/**??????stet?the?lastaccesstime.?????*?@param?latimelong?????

????

????

PUBLIC?

Static?

Void? setlastaccesstime

Long? latime)? {

???????? LastAccesstime = latime

????}

????

/ **??????Sets?the?inuse.?????*?@param?inuseththe?inuse "to?set?????/

????

PUBLIC?

Void? setinuse

Boolean? inuse? {

????????

this.inuse? =? inuse;

????}

????

????

PUBLIC?

SYNCHRONIZED?

Void? release ()? {

????????

Try {

???????????? close ();

????????}

Catch (SQLEXCEPTION? E) {

???????????? log (e,

"ConnectionObject - RELESE? Call? Close? Failed");

????????}

????}

????????

/ ** ???? *? Write text information to log files ???? * /

????

PRIVATE?

Void? log (String? msg)? {

???????? connectionManager.log (msg);

????}

????

????

/ ** ???? *? Write text information with exceptions to log files ???? * /

????

PRIVATE?

Void? log (throwable? e,? String? msg)? {

???????? ConnectionManager.log (e, msg);

????}

}

转载请注明原文地址:https://www.9cbs.com/read-124100.html

New Post(0)