Principles, configuration, and usage of Tomcat data sources

Source: Internet
Author: User

Principles, configuration, and usage of Tomcat data sources
1. The role and operating principle of the data source can be improved by using the data source in the program code. The performance improvement depends on the operating principle.

Traditional JDBC procedure
1. Load the database driver. The database driver is configured through CLASSPATH;
2. Get the database connection object through the DriverManager class;
3. instantiate the PreparedStatement object through Connection and write SQL commands to operate the database;
4. The database is a resource operation. After the operation is completed, the database is closed to release the resource. :

For different users, only operations are different, but steps 1, 2, and 4 are obviously a duplicate operation.

If the JDBC operation is used directly during development, this performance problem will occur. How can this problem be best solved?

If the database is not closed, if a new user uses the database directly to obtain an existing connection.

For example, if the school provides an umbrella for students, they will prepare an umbrella for students when it rains. In this case, students do not have to find an umbrella again, and then buy an umbrella again.

Suppose there are 100 umbrellas. If it doesn't rain now, you certainly won't be able to put all the umbrellas on it. So generally, if no one uses them, you should set at least 10 umbrellas. Of course, up to 100 umbrellas can be provided.

You also need a waiting time.

The minimum number of database connections and the maximum number of opened connections.

    Tomcat 4.1 and later versions began to support this operation. This operation is called the database connection pool, which stores all database connections.

2, Use the database connection pool in Tomcat

   In the web container, the database connection pool uses the data source (javax. SQL. dataSource), that is, it can be accessed through javax. SQL. the DataSource class gets the Connection object, but if you want to get a DataSource object, you need to use JNDI for search.

JNDI (Java Naming and Directory Interface) is a Naming and Directory lookup Interface. Its main function is to find objects.
However, the current database connection pool needs to be configured on Tomcat.

You must modify the server. xml file to make it take effect.

Take mysql as an example:

 1 <Context docBase="D:/data/webdemo" path="/webdemo" debug="0"  reloadable="true"> 2       <Resource name="jdbc/mydb" 3                 auth="Container" 4                 type="javax.sql.DataSource" 5                 maxActive="100" 6                 maxIdle="30" 7                 maxWait="10000" 8                 username="root" 9                 password="root"10                 driverClassName="org.gjt.mm.mysql.Driver"11                 url="jdbc:mysql://localhost:3306/mydb"/>12 </Context>

This configuration has several parameters:
· Name: indicates the data source name and the name to be searched by JNDI.
· Auth: indicates who is responsible for resource connection, Container: Container Management, application: Program Management, generally set to Container
· Type: indicates an object. Each data source is bound with a DataSource.
· MaxActive: indicates the maximum number of activated connections. The value is 100, indicating a maximum of 100 database connections at the same time. Generally, maxActive is set to a possible concurrency.
· MaxIdle: indicates the maximum number of idle connections. The value is 30, which indicates that a 30 idle connection can be maintained even if no database connection is available without being cleared. The connection is always on standby.
· MaxWait: indicates the maximum number of waiting seconds. The value here is 10000, indicating timeout after 10 seconds. If the value is-1, it indicates unlimited waiting until the timeout is reached. If the timeout occurs, an exception is thrown.
· Username: database username
· Password: Database logon password
· DriverClassName: name of the database driver
. Url: Database url

However, the current Tomcat version is later than 6.0, so to make a data source take effect, you must go to the web. xml (Note: This web. xml is the web of a web project. xml file instead of the web. xml file.

1   <resource-ref>2     <res-ref-name>jdbc/mydb</res-ref-name>3     <res-type>javax.sql.DataSource</res-type>4     <res-auth>Container</res-auth>5   </resource-ref>
3. Search for data sources

The Data Source Operation uses the JNDI Method for searching. Therefore, if you want to use the data source to obtain a database connection, you must follow the steps below.
Initialization name search Context: Context ctx = new InitialContext ();
Query the DataSource object by name: DataSource ds = (DataSource) ctx. lookup (JNDI name );
Use DataSource to obtain a database Connection: Connection conn = ds. getConnection ().

In this case, an Exception occurs when you call the database:
Javax. servlet. ServletException: javax. naming. NameNotFoundException: Name jdbc is not bound in this Context
In fact, such resource operations require the support of an environment attribute: java: comp/env. However, the Tomcat server itself is free of charge and does not support this attribute, if you want to access the name service in Tomcat, you must add this attribute before, that is, the current name is: java: comp/env/jdbc/mydb; if Tomcat is used, the JNDI name is: java: comp/env/JNDI name.

In the future, only the name will be recognized in the program, and the specific database will be determined by the configuration.
Of course, if DAO is used for development, DatabaseConnection. java class.

1 package com. shawn. mvcdemo. dbc; 2 3 import java. SQL. *; 4 import javax. SQL. *; 5 import javax. naming. *; 6 7 public class DatabaseConnection {8 private static final String DSNAME = "java: comp/env/jdbc/mldn"; // java: comp/JNDI name 9 10 private Connection conn = null; 11 12 public DatabaseConnection () throws Exception {13 Context ctx = new InitialContext (); // initialize the name query context 14 DataSource ds = (DataSource) ctx. look Up (DSNAME); // query the DataSource object by name 15 this. conn = ds. getConnection (); // get a database Connection through DataSource 16} 17 18 public Connection getConnection () {19 return this. conn; 20} 21 22 public void close () throws Exception {23 if (this. conn! = Null) {24 try {25 this. conn. close (); // release database connection 26} catch (Exception e) {27 throw e; 28} 29} 30} 31 32 public static void main (String args []) {33 try {34 System. out. println (new DatabaseConnection (). getConnection (); 35} catch (Exception e) {36 e. printStackTrace (); 37} 38} 39}

However, you must note that the current database connection pool is actually configured on Tomcat, so this program can only run on the web, rather than running the program using the application.

Summary:

To use the database connection pool

1. configure server. xml;

2. Configure the web. xml file in the web project (for example, webdemo project) and addResource-refConfiguration;

3. Modify the method for obtaining the Connection in the program.

Contact Us

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.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.