This class is implemented in rows 209 through 345, which represents a connection pool that points to a database. The database is identified by the JDBC URL. A JDBC URL consists of three parts: the protocol identifier (always JDBC), the driver identification (such as ODBC, IDB, Oracle, and so on), and the database identity (its format is dependent on the driver). For example, Jdbc:odbc:de
Mo, which is a JDBC URL that points to the demo database, and accesses the database using the JDBC-ODBC driver. Each connection pool has a name for use by the client program and an optional user account, password, maximum number of connections. If some of the database operations supported by a Web application can be performed by all users, while others should be performed by a specially licensed user, a connection pool can be defined for two types of operations, two connection pools use the same JDBC URL, but different accounts and passwords are used.
The constructor for class Dbconnectionpool requires all of the above data as its parameters. As shown in lines 222 through 238, the data is saved as its instance variable:
As shown in rows 252 through 283, 285 to 305, the client program can use the two methods provided by the Dbconnectionpool class to obtain the available connections. The common point is that if there is an available connection in the connection pool, it is returned directly, otherwise a new connection is created and returned. If no connection is available and the total number of connections is equal to the maximum limit
Number, the first method returns null directly, and the second method waits until there is an available connection.
All available connection objects are registered in vectors named freeconnections (vector). If there are more than one connection in the vector, getconnection () always selects the first one. At the same time, because new, available connections always add vectors from the tail, the risk of a database connection being shut down for long periods of time is minimized.
The first getconnection () called the IsClosed () method to verify that the connection is still valid before returning the available connection to the client. If the connection is closed or an exception is triggered, getconnection () recursively calls itself to try to get another available connection. If there are no available links in the vector freeconnections
Next, the Getconnection () method checks whether the maximum number of connections has been specified. If specified, checks to see if the current number of connections has reached the limit. Here Maxconn 0 means there is no limit. If you do not specify the maximum number of connections or the current number of connections is less than this value, the method attempts to create a new connection. If the creation succeeds, the count of the used connection is incremented and returned, otherwise null is returned.
As shown in lines 325 through 345, creating a new connection is implemented by the Newconnection () method. The creation process is related to whether the database account number or password has been specified.
The DriverManager class of JDBC provides multiple getconnection () methods that use JDBC URLs and other parameters, such as user accounts and passwords.
DriverManager will use the specified JDBC URL to determine the driver that is appropriate for the target database and establish the connection.
The second getconnection () method implemented in lines 285 through 305 requires a time parameter in milliseconds, which represents the maximum time that a client program can wait. The exact operation of establishing a connection is still implemented by the first getconnection () method.
When the method executes, the StartTime is initialized to the current time. Try to get a connection in the while loop. If it fails, the wait () is invoked with the given time value as the parameter. The return of Wait () may be due to another thread calling notify () or Notifyall (), or possibly due to a scheduled time. To find the real reason for the return of Wait (), the program uses the current time minus start (starttime), and returns null if the difference is greater than the scheduled time, otherwise the getconnection () is called again.
Registering an idle connection into the connection pool is implemented by the Freeconnection () method of 240 to 250 rows, and its parameters are the connection objects returned to the connection pool. The object is added to the end of the freeconnections vector, and then the connection count is reduced. The call to Notifyall () is to notify other threads that are waiting for an available connection.
Many servlet engines provide several ways to implement secure shutdown. The database connection pool needs to know about the event to ensure that all connections are shut down properly. The Dbconnectionmanager class negatively coordinates the entire shutdown process, but the task of shutting down all connections in the connection pool is owned by the Dbconnectionpool class. The release () method implemented in lines 307 through 323 is for Dbconnectionmanager calls. The method traverses the freeconnections vector and closes all the connections, and then removes them from the vector.
Iv. Description of Class Dbconnectionmanager
The class can only create one instance, and other objects can call its static method (also called a class method) to obtain a reference to that unique instance. As shown in lines 031 through 036, the constructors for the Dbconnectionmanager class are private, in order to prevent other objects from creating instances of the class.
The client program for the Dbconnectionmanager class can call the GetInstance () method to obtain a reference to the unique instance of the class. As shown in rows 018 through 029, a unique instance of a class is created during the first invocation of the getinstance () method, and its reference is then persisted in the static variable instance. GetInstance per call ()
Adds a dbconnectionmanager count of client programs. That is, the count represents the total number of client programs referencing the Dbconnectionmanager unique instance, which will be used to control the shutdown operation of the connection pool.
The initialization of the class instance is done by the private Method init () between 146 and 168 rows. where the getResourceAsStream () method is used to locate and open an external file. The location method of an external file relies on the implementation of the class loader. The standard local class loader lookup operation always starts at the path where the class file resides, and can also search for the path declared in Classpath. Db.properties is a property file that contains key-value pairs that define the connection pool. The common properties that are available for definition are as follows:
Drivers a space-delimited list of JDBC driver classes
LogFile the absolute path of the log file
Other properties are associated with a specific connection pool, and the name of the connection pool should precede the attribute names:
JDBC URL for <poolname>.url database
<poolname>.maxconn Maximum number of connections allowed, 0 means no Limit
<poolname>.user the database account number used for this connection pool
<poolname>.password the appropriate password
Where the URL property is required, and the other properties are optional. The database account number and password must be legal. Example of a db.properties file for the Windows platform
As follows:
Note that the backslash in the Windows path must be entered in 2, because the backslash in the property file is also an escape character.
After creating the Property object and reading the Db.properties file, the init () method begins checking the LogFile property. If the log file is not specified in the property file, the DBConnectionManager.log file in the current directory is assumed to be the default. If the log file is not available, output logging to System.err.
Mounts and registers all the JDBC drivers specified in the drivers property, implemented by the Loaddrivers () method between 170 and 192 rows. The method first splits the drivers property value into a string corresponding to the driver name, then loads the classes and creates the StringTokenizer, and finally registers in the DriverManager
The instance and adds it to a private vector drivers. The vector drivers will be used to cancel the registration of all JDBC drivers from DriverManager when the service is closed.
The last task of the Init () method is to invoke the private method Createpools () to create the connection pool object. As shown in lines 109 through 142, the Createpools () method first creates an enumeration object (that is, the enumeration object, which can be imagined as a series of elements, and then calls its nextelement () method to return the order
Back to the elements), and then search for the attribute whose name ends with ". url". For each eligible attribute, the first part of the connection pool name is extracted, which reads all the attributes that belong to the connection pool, and finally creates the connection pool object and saves it in the instance variable pools. Hash list (Hashtable class) Pools implementation connection
The mapping between the pool name and the connection pool object, where the connection pool name is the key and the connection pool object is a value.
Class Dbconnectionmanager provides methods getconnection () and freeconnection () to facilitate the client to obtain an available connection from the specified connection pool or to return the connection to the connection pool. All of these methods require a connection pool name to be specified in the parameter, and a specific connection fetch or return operation calls the corresponding connection pool object to complete. Their implementations are from 051 to 064 rows, 066 to 080 rows, and 038 to 049 rows respectively.
As shown in lines 082 through 107, Dbconnectionmanager provides method release () for the safe shutdown of the connection pool. As we have mentioned above, all Dbconnectionmanager clients should call the static method getinstance () to obtain a reference to the manager, which will increase the client count.
The client program calls release () at shutdown to decrement the count. When the last client invokes release () and the decremented reference count is 0, you can call the release () method of each connection pool to close all connections. The final task of the Management class release () method is to revoke the registration of all JDBC drivers.
V. servlet use connection pooling example
The servlet lifecycle classes defined by the Servlet API are as follows:
1 Create and initialize the servlet (init () method).
2 Respond to Client service requests (services () method).
3 The servlet terminates the operation, releasing all Resources (Destroy () method).
This example demonstrates the connection pool application, and the relevant actions in the above key steps are:
1 in init (), use the instance variable connmgr to save the reference returned by the call Dbconnectionmanager.getinstance ().
2 in service (), call getconnection (), perform database operations, and return the connection to the connection pool with freeconnection ().
3 in Destroy (), call Release () to close all connections, releasing all resources.
The list of sample programs is as follows:
Import java.io.*;
Import java.sql.*;
Import javax.servlet.*;
Import javax.servlet.http.*;
public class Testservlet extends HttpServlet {
Private Dbconnectionmanager connmgr;
The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion;
products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the
content of the page makes you feel confusing, please write us an email, we will handle the problem
within 5 days after receiving your email.
If you find any instances of plagiarism from the community, please send an email to:
info-contact@alibabacloud.com
and provide relevant evidence. A staff member will contact you within 5 working days.