Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Dbcp, c3p0, jndi in Database connection Pool Technology

2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Database >

Share

Shulou(Shulou.com)06/01 Report--

No matter what persistence technology you use, you must access the database through a data connection, which in Spring is obtained through a data source. In previous applications, data sources are generally provided by Web application servers. In Spring, you can not only obtain the data source of the application server through JNDI, but also configure the data source directly in the Spring container. In addition, you can also create a data source through code for independent unit testing.

Configure a data source

Spring includes two data source implementation class packages in the third-party dependency package, one is Apache's DBCP, and the other is C3P0. You can use either of these two to configure the data source in the Spring configuration file.

DBCP data source

The DBCP class package located in / lib/jakarta-commons/commons-dbcp.jar,DBCP is a database connection pool that relies on the Jakarta commons-pool object pooling mechanism, so / lib/jakarta-commons/commons- pool.jar must also be included under the classpath. The following is a configuration snippet for configuring an MySql data source using DBCP:

Xml code

BasicDataSource provides the close () method to close the data source, so you must set the destroy-method= "close" property so that the data source closes normally when the Spring container closes. In addition to the above required data source properties, there are also some commonly used properties:

DefaultAutoCommit: sets whether the connection returned from the data source uses the auto-commit mechanism. The default value is true.

DefaultReadOnly: sets whether the data source can only perform read-only operations. The default is false.

MaxActive: the maximum number of database connections. If set to 0, there is no limit.

MaxIdle: the maximum number of waiting connections. If set to 0, there is no limit.

MaxWait: the maximum number of seconds to wait (in milliseconds). An error message will be reported when the time is exceeded.

ValidationQuery: the query SQL statement used to verify the success of the connection. The SQL statement must return at least one row of data, such as you can simply set to: "select count (*) from user"

RemoveAbandoned: whether to interrupt itself. Default is false.

RemoveAbandonedTimeout: the data connection will be automatically disconnected after a few seconds. This value is provided for true in removeAbandoned.

LogAbandoned: whether to log interrupt events. Default is false.

C3P0 data source

C3P0 is an open source JDBC data source implementation project that is released with Hibernate in the lib directory and implements the Connection and Statement pools specified in the JDBC3 and JDBC2 extension specifications. The C3P0 class package is located in / lib/c3p0/c3p0-0.9.0.4.jar. The following is to configure an Oracle data source using C3P0:

Xml code

ComboPooledDataSource, like BasicDataSource, provides a close () method to close the data source, so we can ensure that the data source can be successfully released when the Spring container is closed.

C3P0 has richer configuration properties than DBCP, through which you can have a variety of effective control over the data source:

AcquireIncrement: the number of new connections created by C3P0 at one time when the connections in the connection pool run out

AcquireRetryAttempts: defines the number of repeated attempts to obtain a new connection from the database. The default is 30.

AcquireRetryDelay: interval between connections (in milliseconds). Default is 1000.

AutoCommitOnClose: all uncommitted operations are rolled back by default when the connection is closed. Default is false

AutomaticTestTable: C3P0 will create an empty table called Test and test it with its own query statement. If this parameter is defined, the property preferredTestQuery is ignored. You can't do anything on this Test table. It will be used for C3P0 testing. The default is null.

BreakAfterAcquireFailure: failure to get a connection will cause all threads waiting to acquire the connection to throw an exception. However, the data source is still valid, and the next time you call getConnection (), you continue to try to get the connection. If set to true, the data source will declare that it has been disconnected and permanently closed after an attempt to obtain a connection fails. Default is false

CheckoutTimeout: the amount of time the client waits to get a new connection after calling getConnection () when the connection pool runs out. After the timeout, SQLException is thrown. If set to 0, it waits indefinitely. Unit millisecond, default is 0

ConnectionTesterClassName: test the connection by implementing a class of ConnectionTester or QueryConnectionTester, with the class name set to fully qualified. Default is com.mchange.v2.C3P0.impl.DefaultConnectionTester

IdleConnectionTestPeriod: how many seconds does it take to check idle connections in all connection pools? default is 0, which means no check.

InitialPoolSize: the number of connections created during initialization, which should be between minPoolSize and maxPoolSize. The default is 3

MaxIdleTime: maximum idle time, connections that exceed idle time will be discarded. If it is 0 or negative, it is never discarded. Default is 0

MaxPoolSize: the maximum number of connections retained in the connection pool. The default is 15

A standard parameter for maxStatements:JDBC that controls the number of PreparedStatement loaded in the data source. However, because the pre-cached Statement belongs to a single Connection rather than the entire connection pool. Therefore, many factors need to be taken into account in setting this parameter. If both maxStatements and maxStatementsPerConnection are 0, the cache is turned off. Default is 0

MaxStatementsPerConnection: the maximum number of cached Statement owned by a single connection in the connection pool. Default is 0

NumHelperThreads:C3P0 operates asynchronously, and slow JDBC operations are done by helping the process. Extending these operations can effectively improve performance and enable multiple operations to be performed at the same time through multithreading. The default is 3

PreferredTestQuery: defines the test statement that all connection tests execute. In the case of connection testing, this parameter can significantly improve the testing speed. The tested table must exist at the time of the initial data source. Default is null

PropertyCycle: the maximum number of seconds a user can wait before modifying system configuration parameters. The default is 300

TestConnectionOnCheckout: because of the high performance consumption, please use it only when needed. If set to true, then the validity of each connection will be verified when it is submitted. IdleConnectionTestPeriod or automaticTestTable is recommended

And other methods to improve the performance of connection testing. Default is false

TestConnectionOnCheckin: if set to true, the validity of the connection will be verified while the connection is obtained. The default is false.

Reference properties in the way you read the configuration file:

Define attribute values in the jdbc.properties properties file:

Jdbc.driverClassName= com.mysql.jdbc.Driver

Jdbc.url= jdbc:mysql://localhost:3309/sampledb

Jdbc.username=root

Jdbc.password=1234

Tips: developers often accidentally type spaces around ${xxx}. These space characters will be merged with variables as the value of the attribute. Such as: property configuration items, there are spaces before and after, after parsing, the value of username is "1234", which will cause the final error, so you need to be very careful.

Get JNDI data source

If the application is configured on a high-performance application server (such as WebLogic or Websphere), we may prefer to use the data sources provided by the application server itself. The data source of the application server is used by JNDI open callers, and Spring specifically provides JndiObjectFactoryBean classes that reference JNDI resources for this purpose. Here is a simple configuration:

Xml code

Specifies the name of the referenced JNDI data source through jndiName.

Spring 2.0 provides a jee namespace for obtaining J2EE resources, and through the jee namespace, references to J2EE resources can be effectively simplified. The following is the configuration for referencing an JNDI data source using the jee namespace:

Xml code

Data source implementation class of Spring

Spring itself also provides a simple data source implementation class DriverManagerDataSource, which is located in the org.springframework.jdbc.datasource package. This class implements the javax.sql.DataSource interface, but it does not provide a pooled connection mechanism, and each time you call getConnection () to get a new connection, you simply create a new one. Therefore, this data source class is more suitable for use in unit testing or simple stand-alone applications, because it does not require additional dependent classes.

Next, let's take a look at the simple use of DriverManagerDataSource: of course, we can also use DriverManagerDataSource directly through configuration.

Java code

DriverManagerDataSource ds = new DriverManagerDataSource (); ds.setDriverClassName ("com.mysql.jdbc.Driver"); ds.setUrl ("jdbc:mysql://localhost:3309/sampledb"); ds.setUsername ("root"); ds.setPassword ("1234"); Connection actualCon = ds.getConnection ()

Summary

No matter what persistence technology you use, you need to define a data source. Spring comes with an implementation class package for two data sources, which you can choose to define. In the actual deployment, we may directly adopt the data source provided by the application server itself, in this case, we can reference the data source in the JNDI through the JndiObjectFactoryBean or jee namespace.

Differences between DBCP and C3PO configurations:

C3PO: DBCP:

Xml code

Oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@10.10.10.6:1521:DataBaseName testAdmin 123456

Xml code

Oracle.jdbc.driver.OracleDriver jdbc:oracle:thin:@10.10.10.6:1521:DataBaseName testAdmin 123456

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Database

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report