Java program database connection, data source configuration, database connection pool __c#

Source: Internet
Author: User
Tags connection pooling
Java Program database connection, data source configuration, database connection pool

Java program, use the database must configure the data source ?

General write small program directly in the program to set up a connection, and large systems generally to configure the data source

The data source is to configure to the middleware server (for example: Tomcat,jboss,weblogic Class), after configuration can improve database query performance, avoid repeatedly open and close the database. So when the Java B/S project is developed (that is, the project, accessed through the browser), the data source connection will be configured. If you write the management software is b/s structure, then only need to build the environment of the server to configure the data source can be, the user access is through the browser access, do not need to do other settings. If it is C/s (that is, users need to install a separate client program, such as QQ), also do not need to set up a data source in the user, only need to be in your server-side program manually configure the data source can be. Java to implement database operations, now most popular is JDBC, the use of configuration data sources are most of the reasons for the framework, such as Hibernate, EJB, Struts, Spring. However, all data source configuration principles are based on JDBC operations. 1. Direct Coded Connection Database

JDBC (Java Database connectivity)

JDBC accesses a wide variety of databases in a unified way, and JDBC hides different features of different databases for developers. When a programmer develops an application that knows to develop access to the database, it encodes a reference to the JDBC driver class for a corresponding database and connects to the database by using the appropriate JDBC URL.

code example:

or by configuring the property file:

These are traditional practices that typically do not create problems in a small-scale development process, so long as programmers are familiar with the Java language, understand JDBC technologies, and various databases, they can quickly develop appropriate applications.

The problem that this approach poses:

1, the database server name, user name and password may need to change, which triggers the JDBC URL needs to be modified;
2, the database may switch to other products, such as using DB2 or Oracle, to trigger the JDBC driver package and class name needs to be modified;
3, with the actual use of the terminal increase, the original configuration of the connection pool parameters may need to adjust;

Solution:
Programmers should not be concerned about what the specific database backend is. What is the JDBC driver. What is the JDBC URL format. What is the user name and password to access the database. "And so on, programmers should write a program that doesn't have a reference to the JDBC driver, no server name, no user name or password--not even a database pool or connection management." Instead, these problems are given to the Java container for configuration and management, and the programmer only needs to refer to these configurations and management. From this, there is jndi, configuring the data source. 2. Configure the data source

JNDI (Java naming and Directory Interface)

The JNDI API is used to perform name and directory services. It provides a consistent model for accessing and manipulating enterprise-class resources such as DNS and LDAP, the local file system, and the object in the application server. In Jndi, each node in the directory structure is called a context. Each jndi name is relative to the context. The application can use this initialized context to locate the resource or object it needs through this directory tree.

Configuring a data source for a connection in Tomcat

Obtain a DataSource reference through the Jndi service in Tomcat and obtain a database connection through DataSource, as follows:
1. Configure the data source Jndi service
2. Use the Javax.naming.Context lookup method in the application to retrieve the datasource reference
3. DataSource Getconnection method to obtain the connection

To configure the code for the Jndi service:

Configuration file Contents:

In the application, the Javax.naming.Context lookup method is used to retrieve the datasource reference through Jndi, and the database connection is obtained by DataSource:

The amount of programming code that uses JDBC directly or through a Jndi reference data source is almost the same, but now the program does not have to worry about the specific JDBC parameters. After system deployment, if the parameters of the database change, only need to modify the JDBC parameters in the configuration file, so long as the data source name is guaranteed unchanged, then the program source code need not be modified. Thus, Jndi avoids the tight coupling between the program and the database, making the application easier to configure and easier to deploy. Jndi, which meets the requirements of the data source configuration, further expands its role: all references to resources outside the system can be defined and referenced through Jndi. Therefore, in the Java EE specification, the resources in Java EE are not limited to the JDBC data source. There are many types of references, including resource references, environment entities, and EJB references. In particular, EJB references expose the other key role of JNDI in Java EE: finding other application components. A JNDI reference to an EJB is very similar to a reference to a JDBC resource. This is a very effective method in an environment where services tend to transition. This configuration management can be done for all the components that are available in the application architecture, from EJB components to JMS queues and themes to simple configuration strings or other objects, which can reduce the maintenance costs of service changes over time, while simplifying deployment and reducing integration efforts.

The Java EE specification requires all Java-EE containers to provide a JNDI specification implementation. The role of JNDI in Java EE is a common mechanism for the "switch"--J2EE component to indirectly find other components, resources, or services at run time. In most cases, the container that provides the JNDI provider can act as a limited data store, so the administrator can set the execution properties of the application and have other applications reference these properties (Java Management Extensions, Java Management extensions, JMX) can also be used for this purpose. The main role of JNDI in the Java EE application is to provide an indirect layer so that the component can discover the resources needed without having to understand these indirection. In Java EE, Jndi is the glue that puts the Java application together, and the indirect addressing provided by Jndi allows scalable, powerful, and flexible applications to be delivered across the enterprise. 3. Database Connection Pool

Connection pooling is a technique for creating and managing multiple connections that can be used by any thread that needs to use them. The connection pooling technology is based on the fact that for most applications, only 1 threads that have access to the JDBC connection are needed when they are dealing with transactions that typically require a few milliseconds to complete. When a transaction is not processed, the connection is idle. Use connection pooling to allow other threads to perform useful tasks using idle connections. In fact, when a thread needs to use JDBC to perform operations on MySQL or another database, the connection provided by the connection pool needs to be used. When you use a connection to complete a 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 connecting from a connection pool, this connection is only used by the thread that requested it. From a programmatic standpoint, the effect is equivalent to calling Drivermanager.getconnection () each time a JDBC connection is required, but with connection pooling technology, you can end a thread by using a new or existing connection. Connection pooling technology can significantly increase the performance of Java applications, while also reducing resource usage.

key advantages of connection pooling technology include:

(1) Shortened connection creation time

Creating a new JDBC connection can result in networked operations and a certain amount of JDBC-driven overhead, which can be avoided if such connections are used in a "looping" manner.

(2) simplified programming model

With connection pooling technology, each individual thread can operate as if it had created its own JDBC connection, allowing the use of direct JDBC programming techniques.

(3) Controlled use of resources

If you do not use connection pooling technology, but instead create a new connection for the thread every time you need it, the application's resource usage is wasteful and can cause unpredictable results when the load is heavy.

Note that each connection to the database causes a certain amount of overhead (CPU, association conversion, etc.) on the client and server side. Each connection has a limited amount of resources available to the application and to the database server. A significant portion of these resources will be used regardless of whether the connection performs any useful tasks.

Connection pooling maximizes performance while at the same time controlling resource utilization to a certain level, and if that level is exceeded, the application crashes rather than slows down.

Fortunately, Sun has completed the standardized implementation of the connection pool concept in JDBC through the JDBC-2.0 "optional" interface, with all major application servers implementing such APIs that can work well with MySQL connector/j.

Typically, you can configure the connection pool in the application server's configuration file and access it through the Java Naming and directory interface (JNDI). The most important thing to keep in mind when using connection pooling is that no matter what appears in your code (exceptions, control flows, and so on), the connection and any parts created by the connection (statements, result sets, and so on) should be closed so that they can be used again. If not, they will be entangled together, in the best case, meaning that the database server resources they represent (buffers, locks, sockets, etc.) may be bundled for a period of time and, in the worst case, may lead to permanent binding.

What is the best size for the connection pool?

Depends on the specific situation. Although the optimal size depends on the expected load and the average database transaction time, the best connection pool size is smaller than you expected. For example, if you are using a sun Company's Java petstore Blueprint application, MySQL and Tomcat are available to serve a moderate load (600 concurrent users) for a connection pool that contains 15~20 connections, in the appropriate time acceptable. To determine the connection pool size for your application, you should use tools such as the Apache JMeter or the grinder to create load test scripts and load test your application. An easy way to determine the starting point is to configure the maximum number of connections for the connection pool to unlimited, run the load test, and measure the maximum number of concurrent connections. Subsequently, you should reverse the operation to determine the minimum and maximum number of connection pools to which the application has the best performance.

The connection pool differs from the data source.

Database connection pooling establishes enough database connections at application startup and makes these connections a pool of connections that the application dynamically applies, uses, and releases to connections in the pool. For concurrent requests that have more than the number of connections in the connection pool, wait in the queue for the request. And the application can dynamically increase or decrease the number of connections in the pool, depending on the usage of the connection in the pool. When the connection operation is turned off, the connection is not really shut down, but is returned to the connection pool as an idle connection to continue to use later, and the connection pooling technology resolves the performance problems caused by the frequent open shutdown of the database connection.

With the connection pool, we don't have to deal directly with the data source, the connection pool is in your program's machine memory, the data source is not necessarily, and the data source and connection pool will maintain a certain number of connections, so that we access the database when we do not need to find the data source to connect, directly in the local memory to get the connection, You can improve the performance of your program. The link pool exists for efficiency because instantiating a connection is resource-intensive and has a reusable feature, so you can put a certain number of connections in the pool to improve efficiency.

database connection pool management with Tomcat

C3P0 Database Connection Pool

Database connection Pool Configuration code:

Configuration file:

"Reference synthesis"

Http://hi.baidu.com/sunkangle/blog/item/55a9db7cb076a3330dd7dadb.html

Comparison between JDBC and Jndi application

http://13243356.javaeye.com/blog/402961

Database connection and Data source configuration

Http://hi.baidu.com/yaoming159/blog/item/5c4efe33e2122df31a4cfff5.html

JDBC and Jndi differences

Http://wenwen.soso.com/z/q155303937.htm?pid=wenwen.autologin

Must the Java database be configured with a data source?

Http://hi.baidu.com/begin_think/blog/item/b959f9f45b67092ebd310973.htmlJNDI

Comparison with JDBC and the technology of connection pooling

Http://topic.csdn.net/u/20090311/10/f6ee00c1-34ed-42ef-b5aa-77d2c7a8e775.html

What does the connection pool have to do with the data source, respectively?

Finishing

by Willowind

Related Article

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.