Java program database connection, data source configuration, database connection pool
For Java programs, do I have to configure the data source for the databases used?
Generally, you can set the connection directly in the program by writing a small program, while a large system generally needs to configure the data source.
The data source must be configured on the middleware server (such as Tomcat, JBoss, and WebLogic). After configuration, the database query performance can be improved to avoid repeated opening and closing of the database. Therefore, when developing a Java B/S project (a J2EE project, a project accessed through a browser), data source connections are configured. If the management software you write is in the B/S structure, you only need to configure the data source on the server where the environment is set up. Users can access the software through a browser without additional settings. If it is C/S (that is, the user needs to install the client program separately, such as QQ), and does not need to set the data source in the user, you only need to manually configure the data source on your server program. Java implements database operations, most of which are now popular with JDBC. Most of the methods for configuring data sources use the framework, such as Hibernate, EJB, struts, and spring. However, the configuration principles of all data sources are JDBC-based.
1. Connect to the database through direct encoding
JDBC (Java database connectivity)
JDBC accesses a variety of databases in a unified way. JDBC hides different features of different databases for developers. When developers know that they want to develop applications that access the database, They encode the reference of the JDBC Driver Class of the corresponding database and connect to the database by using the appropriate jdbc url.
Sample Code:
You can also configure the property file as follows:
The above are all traditional practices. This practice will not cause problems during small-scale development. As long as programmers are familiar with the Java language, JDBC technology, and various databases, you can quickly develop applications.
Problems caused by this method:
1. The database server name, user name, and password may need to be changed, resulting in the jdbc url needing to be modified;
2. The database may use another product. For example, if you use DB2 or Oracle, The JDBC driver package and class name must be modified;
3. As the number of terminals in use increases, the original connection pool parameters may need to be adjusted;
Solution:
Programmers do not need to worry about "what is the specific database background? What is the JDBC driver? What is the jdbc url format? What is the user name and password used to access the database ?" And so on, the program compiled by the programmer should not reference the JDBC driver, no server name, no user name or password-or even no database pool or connection management. Instead, the problem is assigned to the J2EE container for configuration and management. The programmer only needs to reference the configuration and management. As a result, JNDI is available to configure the data source.
2. Configure the data source
JNDI (Java Naming and Directory Interface)
The jndi api is used to run the name and directory services. It provides a consistent model to access and operate enterprise-level resources such as DNS and LDAP, local file systems, and the latter's objects on the application server. In JNDI, each node in the directory structure is called context. Each JNDI name is relative to context. The app can use this initialized context to locate the resources or objects it needs through this directory tree.
Configure the data source in Tomcat to get the connection
Obtain the datasource reference through the JNDI service in Tomcat and obtain the database connection through the datasource. The steps are as follows:
1. Configure the data source JNDI Service
2. In the application, use the lookup method of javax. Naming. Context in JNDI to retrieve datasource references.
3. Get the connection using the getconnection method of datasource
Code for configuring the JNDI service:
Configuration File Content:
In the application, the datasource reference is retrieved using the lookup method of javax. Naming. context through JNDI. The datasource obtains the database connection:
The amount of programming code for directly using JDBC or referencing a data source through JNDI is almost the same, but the current program does not need to care about specific JDBC parameters. After the system is deployed, if the database parameters change, you only need to modify the JDBC parameters in the configuration file. As long as the data source name remains the same, the program source code does not need to be modified. It can be seen that JNDI avoids the tight coupling between the program and the database, making the application easier to configure and deploy. In addition to meeting the data source Configuration Requirements, JNDI further expands its role: All references to resources outside the system can be defined and referenced through JNDI. Therefore, in the J2EE specification
The resources in are not limited to JDBC data sources. There are many types of references, including resource reference, Environment entity, and EJB reference. In particular, EJB references expose another key role of JNDI in J2EE: Find other application components. The JNDI reference of EJB is very similar to the reference of JDBC resources. In an environment where services tend to be converted, this is a very effective method. This type of configuration management can be performed on all components in the application architecture, from EJB components to JMS queues and topics, to simple configuration strings or other objects, this can reduce the maintenance costs incurred by service changes over time, simplify deployment, and reduce integration work.
The J2EE specification requires that all J2EE containers provide the implementation of the jndi specification. The role of JNDI in J2EE is "vswitch". During the operation of J2EE components, the common mechanism of other components, resources, or services is indirectly searched. In most cases, the container that provides the JNDI supplier can act as a limited data storage, so that the administrator can set the execution attribute of the application, and let other applications reference these attributes (Java Management Extensions (JMX) can also be used for this purpose ). JNDI in J2EE
The main role in the application is to provide an indirect layer, so that the component can discover the required resources without understanding these indirect properties. In J2EE, JNDI is the binder that combines J2EE applications. The indirect addressing provided by JNDI allows cross-enterprise delivery of scalable, powerful, and flexible applications.
3. Database Connection Pool
A connection pool is a technology used to create and manage multiple connections. These connections can be used by any thread that needs them. The connection pool technology is based on the fact that most applications only need to be able to access one thread of a JDBC connection when they are processing transactions that usually take several milliseconds to complete. When the transaction is not processed, the connection is idle. Use the connection pool to allow other threads to use idle connections to execute useful tasks. In fact, when a thread needs to use JDBC to perform operations on MySQL or other databases, the connection provided by the connection pool is used. After the connection is used to complete the thread, the thread returns the connection to the connection pool so that the connection can be used by other threads that need to use the connection. When a connection pool is used to "lend" a connection, the connection is only used by the thread requesting it. From the programming point of view, the effect is equivalent to calling drivermanager. getconnection () every time a JDBC connection is required. However, using the connection pool technology, you can end a thread by using a new or existing connection. The connection pool technology can significantly increase the performance of Java applications and reduce resource usage.
The connection pool technology has the following advantages:
(1) Shorten the connection Creation Time
Creating a New JDBC connection will lead to network operations and a certain JDBC driver overhead. If such connections are "circulating", this method can be used to avoid such adverse factors.
(2) simplified programming model
When using the connection pool technology, each separate thread can operate as if it had created its own JDBC connection, thus allowing direct JDBC programming technology.
(3) controlled resource usage
If you do not use the connection pool technology, but create a new connection for the thread each time you need it, the resource usage of the application will be wasted, in addition, when the load is heavy, unexpected results may occur.
Note that each connection to the database causes a certain amount of overhead (CPU, associated conversion, etc.) on the client and server ). Each connection imposes certain restrictions on the available resources of applications and database servers. A considerable portion of these resources will still be used regardless of whether the connection executes any useful tasks.
The connection pool maximizes performance and controls resource utilization to a certain level. If it exceeds this level, the application will crash, not just slow down.
Fortunately, Sun completed the standardized implementation of the Connection Pool concept in JDBC through the JDBC-2.0 "optional" interface, all major application servers have implemented such APIs that can work well with MySQL ctor/J.
Generally, you can configure the connection pool in the configuration file of the application server and access it through the Java Naming and Directory Interface (JNDI. The most important thing to remember when using the connection pool is that no matter what happens in the Code (exceptions, control flow, etc.), the connection and any part created by the connection (statements, result sets, etc) they should be disabled so that they can be used again. Otherwise, they will be entangled. In the best case, it means that the database server resources they represent (buffers, locks, sockets, etc.) may be bundled for a period of time, in the worst case, it may lead to a permanent bundle.
What is the optimal size of the connection pool?
Depends on the specific situation. Although the optimal size depends on the expected load and average database transaction time, the optimal connection pool size is smaller than you expected. For example, if Sun's Java PetStore blueprint application is used ~ 20 connection pools using MySQL and tomcat can serve a moderate load (600 concurrent users) at an acceptable time ). To determine the size of the connection pool used for the application, use tools such as Apache jmeter or the grinder to create a load test script and perform load tests on the application. A simple way to determine the starting point is to set the maximum number of connections in the connection pool to "unlimited", run the load test, and measure the maximum number of concurrent connections. Then, the reverse operation should be performed to determine the minimum and maximum values of the connection pool for the application to have the best performance.
What is the difference between a connection pool and a data source?
The database connection pool is used to establish sufficient database connections when the application starts and form a connection pool. The application dynamically applies for, uses, and releases the connections in the pool. For concurrent requests that exceed the number of connections in the connection pool, wait in the Request queue. In addition, applications can dynamically increase or decrease the number of connections in the pool based on the connection usage in the pool. When the connection is closed, the connection is not actually closed. Instead, it is returned to the connection pool as a idle connection and continues to be used later. The connection pool technology solves the performance problems caused by frequent opening and closing of database connections.
With the connection pool, we don't have to deal with the data source directly. The connection pool is in the memory of the machine where your program is located. The data source is not necessarily, and the data source and connection pool will maintain a certain number of connections, in this way, we do not need to connect to the data source when accessing the database, and directly connect to the local memory, which can improve the program performance. The existence of a connection pool is for efficiency. Because it is resource-consuming to instantiate a connection and the connection has reusable features, a certain number of connections can be placed in the connection pool to improve efficiency.
Tomcat database connection pool management
C3p0 database connection pool
Database Connection Pool configuration code:
Configuration file:
[Reference Material Synthesis]
Http://hi.baidu.com/sunkangle/blog/item/55a9db7cb076a3330dd7dadb.html
Comparison between JDBC and JNDI applications
Http://13243356.javaeye.com/blog/402961
Database Connection and data source configuration
Http://hi.baidu.com/yaoming159/blog/item/5c4efe33e2122df31a4cfff5.html
Difference between JDBC and JNDI
Http://wenwen.soso.com/z/q155303937.htm? PID = Wenwen. autologin
Do I have to configure a data source for a Java database?
Http://hi.baidu.com/begin_think/blog/item/b959f9f45b67092ebd310973.htmlJNDI
Comparison with JDBC and connection pool technology
Http://topic.csdn.net/u/20090311/10/f6ee00c1-34ed-42ef-b5aa-77d2c7a8e775.html
What is the role of the connection pool and data source?
Organize
By willowind