Improve the efficiency of servlet access database with a connection pool (below)

xiaoxiao2021-03-06  99

Third, class DBConnectionPool Description

This class is implemented in 209 to 345, which represents the connection pool to a database. The database is identified by the JDBC URL. A JDBC URL consists of three parts: protocol identifier (always JDBC), driver ID (such as ODBC, IDB, ORACLE, etc.), database identity (its format depends on the driver). For example, JDBC: ODBC: Demo is a JDBC URL pointing to the DEMO database, and accesses the database to use the JDBC-ODBC driver. Each connection pool has a name for the client and an optional user account, password, maximum connection limit. If some database operations supported by the web application can be executed by all users, while other operations should be performed by special licensed users, they can define the connection pool for two types of operations, and the two connecting pools use the same JDBC URL, But use different accounts and passwords.

The construction function of class DBConnectionPool requires all of the above data as its parameters. As shown in 222 to 238, these data are saved as their instance variable:

For example, 252 to 283 lines, 285 to 305 lines, the client can obtain the available connections using the two methods provided by the DBConnectionPool class. The commonality is that there is a available connection in the connection pool, but it will return directly, otherwise create a new connection and returns. If there is no connection available and the total number of connections is equal to the maximum limit, the first method will return directly to NULL, and the second method will wait until there is available connection.

All available connection objects are registered in the vector (Vector) called FreeConnections. If there are more connections in the vector, getConnection () always selects the first. At the same time, since the new available connection is always added from the tail, the database connection is reduced to the lowest degree due to long-term idleness.

The first getConnection () calls the isclosed () method to verify the connection is still valid before returning to the client. If the connection is turned off or triggered, getConnection () recursively calls yourself to attempt to get additional available connections. If there is no available connection in the vector freeConnections, the getConnection () method checks if the maximum connection limit is specified. If you have already specified, check if the current connection has reached the limit. There is no limit to the MAXCONN 0 here. If the maximum number of connections is not specified or the current connection is less than this value, the method attempts to create a new connection. If you create success, add a count that has been used and returned, otherwise return null value.

As shown in the 325 to 345 line, create a new connection is implemented by the newconnection () method. The creation process is related to whether the database account has been specified, the password is related.

JDBC's DriverManager class provides multiple getConnection () methods, which use the JDBC URL and other parameters such as user accounts and passwords. DriverManager determines the driver that is suitable for the target database with the specified JDBC URL and establishes the connection.

The second getConnection () method implemented at 285 to 305 rows requires a time parameter in milliseconds, which indicates the maximum time of the client to wait. The specific operation of establishing a connection is still implemented by the first getConnection () method.

This method is executed to initialize the startTime to the current time. Try a connection in the While loop. If it fails, call WAIT () is called with a given time value. The return of Wait () may be due to other threads to call notify () or notifyall (), or may be due to the predetermined time. To find the real cause of Wait () returned, the program is used to reduce the start time (startTime), if the difference is greater than the predetermined time, returns a null value, otherwise getConnection () again. Register idle connections to the connection pool by a 240 to 250 line FREECONNECTION () method implementation, its parameters are the connection object that is returned to the connection pool. This object is added to the end of the FreeConnections vectors, and then reduces the use of the connection count. Calling NotifyAll () is to inform the other thread that is waiting for the available connection.

Many servlet engines provide a variety of ways to implement security shutdown. The database connection pool needs to be aware of the event to ensure that all connections can be turned off. DBConnectionManager class negative coordinates the closing process, but the task of all connected connections is turned off by the DBConnectionPool class. The Release () method implemented at 307 to 323 rows is called by DBConnectionManager. This method traverses the FreeConnections vector and closes all connections, then removes these connections from the vector.

Fourth, class DBConnectionManager description

This class can only create an instance, and other objects can call their static methods (also known as class methods) to obtain references to the unique instance. As shown in the 031 to 036, the construction function of the DBConnectionManager class is private, which is to avoid instances of other objects to create this class.

The client of the DBConnectionManager class can call the getInstance () method to get a reference to the unique instance of this class. As shown in the 018 to 029 line, the unique example of the class is created during the GetInstance () method, which is created during the call, which will now be stored in the static variable instance. Each time you call getInstance () add a DBConnectionManager's customer count. That is, the count represents the total number of client programs that reference the DBConnectionManager unique instance, which will be used to control the closing operation of the connection pool.

The initialization of this class is completed by the private method init () between 146 to 168 lines. Where the getResourceAsStream () method is used to locate and open the external file. The positioning method of external documents depends on the implementation of the class loader. The standard local type loader lookup operation always begins the path where the class file is located, and it is also possible to search the path declared in classpath. Db.properties is a property file that contains the key-value pair that defines the connection pool. The common attributes available for definition are as follows:

Drivers List by space-separated JDBC driver class

Logfile log file absolute path

Other properties are related to a particular connection pool, and the name of the connection should be added before the name of the property:

. JDBC URL of .url database

.maxconn allows the maximum number of connections to be established, 0 indicates that there is no limit

.user Database account for this connection pool

.password corresponding password

The URL attribute is required, while other properties are optional. The database account account and password must be legitimate. DB.Properties file for Windows platforms is as follows:

Drivers = sun.jdbc.odbc.jdbcodbcdriver JDBC.IDBDriver

Logfile = d: //user/src//java//dbconnectionmanager//log.txt

IDB.URL = JDBC: IDB: C: //local//javawebserver1.1//db//db.prpidb.maxconn=2

Access.url = JDBC: ODBC: Demo

Access.user = DEMO

Access.password = Demopw

Note that the backslash in the Windows path must be input 2, which is because the backslash in the properties file is also a escape character.

The init () method begins to check the logfile property after creating a property object and reading the DB.Properties file. If you do not specify a log file in the properties file, the DBConnectionManager.log file in the current directory is default. If the log file cannot be used, the log record is output to System.err.

Loading and register all the JDBC drivers specified in the DRIVERS attribute implementation of the loadDrivers () method between 170 to 192 lines. This method first uses StringTokenizer to split the drivers attribute value to a string corresponding to the driver name, and then load these classes and create its instance, and finally register this instance in the DriverManager and add it to a private vector Drivers. Vector Drivers will cancel all JDBC drivers from DRIVERMANAGER to close the service.

The last task of the init () method is to call the private method CreatePools () Create a connection pool object. For example, the CreatePools () method first creates an enumeration object of all attribute names (ie ENUMERATION object, the object can be imagined as a element series, and call its nextElement () method to return each element), then The search name is the attribute ending with ".url". For each of the qualified properties, first extract its connection pool name, and then read all properties belonging to the connection pool, and finally create the connection pool object and save it in the instance variable pools. Hash Table (Hashtable Class) Pools implements the mapping between the connection pool name to the connection pool object, here the connection pool name is key, the connection pool object is the value.

To facilitate customer programs to get available connections from the specified connection pool or return the connection to the connection pool, class DBConnectionManager provides methods getConnection () and FreeConnection (). All of these methods require that the connection pool name is specified in the parameter, the specific connection acquisition or return operation calls the corresponding connection pool object to complete. Their implementations are from 051 to 064, 066 to 080 rows, 038 to 049.

As shown in the 082 to 107 lines, the security shutdown of the connection pool is achieved, and DBConnectionManager provides methods Release (). In the above, we have mentioned that all DBConnectionManager's clients should call the static method getInstance () to get a reference to the manager, which will increase the customer count. The client calls Release () can decrement the count when shutting down. When the last customer program is called Release (), the decremented reference count is 0, you can call the Release () method of each connection pool to close all connections. The Last task of the management class Release () method is to revoke all JDBC drivers registration.

V. SERVLET uses the connection pool example

The servlet life cycle class defined by the Servlet API, such as:

1) Create and initialize the servlet (Init () method).

2) Respond to the service request of the client (Service () method).

3) The servlet is terminated, releases all resources (Destroy () method).

This example demonstrates the connection pool application, the relevant operations in the above key steps are:

1) In init (), save the reference to dbconnectionManager.getInstance () with instance variable connmgr. 2) In Service (), call getConnection (), execute the database operation, and return the connection to the connection pool with freeConnection.

3) In Destroy (), call Release () to close all connections, release all resources.

The sample program list is as follows:

Import java.io. *;

Import java.sql. *;

Import javax.servlet. *;

Import javax.servlet.http. *;

Public class testservlet extends httpservlet {

Private DBConnectionManager Connmgr;

Public void init (servletconfig conf) throws servletexception {

Super.init (conf);

CONNMGR = dbconnectionmanager.getinstance ();

}

Public Void Service (httpservletRequest Req, httpservletResponse res)

THROWS IOEXCEPTION {

Res.SetContentType ("text / html");

PrintWriter out = res. maxwriter ();

Connection con = connmgr.getConnection ("iDB");

IF (con == null) {

Out.println ("You cannot get database connections.");

Return;

}

ResultSet RS = NULL;

ResultSetMetAdata MD = NULL;

Statement Stmt = NULL;

Try {

STMT = con.createstatement ();

RS = stmt.executeQuery ("Select * from Employee);

MD = rs.getMetadata ();

Out.println ("

Data ");

While (rs.next ()) {

Out.println ("
");

For (int i = 1; i

Out.print (rs.getstring (i) ",")

}

}

Stmt.close ();

Rs.close ();

}

Catch (SQLException E) {

E.PrintStackTrace (OUT);

}

Connmgr.FreeConnection ("iDB", con);

}

Public void destroy () {

CONNMGR.RELEASE ();

Super.destroy ();

}

}

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

New Post(0)