Spring integrates hibernate, 5 ways to configure data sources

Regardless of the persistence technology used, a data source needs to be defined. Spring provides four different forms of data source configuration:

Spring 's own data source ( DriverManagerDataSource ), DBCP data source, C3P0 data source, JNDI data source.

1. Spring's own data source

DriverManagerDataSource

XML code:

 

[html]  view plain  copy
 
  1. <bean id="dataSource"     
  2.       class="org.springframework.jdbc.datasource.DriverManagerDataSource">     
  3.     <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
  4.     <property name="url" value="jdbc:oracle:thin:@10.1.9.171:1521:ORCL" />  
  5.     <property name="username" value="xzzzq" />     
  6.     <property name="password" value="xzzzq" />  
  7. </bean>  

 

2. DBCP data source

    The configuration of DBCP depends on two jar packages commons-dbcp.jar and commons-pool.jar.

XML code:

 

[html]  view plain  copy
 
  1. <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource"         
  2.         destroy-method="close">         
  3.     <property name="driverClassName" value="oracle.jdbc.driver.OracleDriver" />  
  4.     <property name="url" value="jdbc:oracle:thin:@10.1.9.171:1521:ORCL" />  
  5.     <property name="username" value="xzzzq" />     
  6.     <property name="password" value="xzzzq" />        
  7. </bean>   

 

Explanation of the above code:

BasicDataSource provides the close() method to close the data source, so the destroy-method=”close” attribute must be set so that when the Spring container is closed, the data source can be closed normally. In addition to the above required data source attributes, there are also some commonly used attributes: 
    defaultAutoCommit: Set whether the connection returned from the data source adopts the automatic commit mechanism, the default value is true; 
    defaultReadOnly: Set whether the data source can only perform read-only operations, The default value is false; 
    maxActive: the maximum number of database connections, when set to 0, it means there is no limit; 
    maxIdle: the maximum number of waiting connections, when set to 0, it means there is no limit; 
    maxWait: the maximum number of seconds to wait, in milliseconds , an error message will be reported if the time is exceeded; 
    validationQuery: The query SQL statement used to verify whether the connection is successful. The SQL statement must return at least one row of data. For example, you can simply set it as: "select count(*) from user"; 
    removeAbandoned : Whether to self-interrupt, the default is false; 
    removeAbandonedTimeout: The data connection will be automatically disconnected after a few seconds, if removeAbandoned is true, provide this value; 
    logAbandoned: Whether to record the interruption event, the default is false;

3. C3P0 data source

     C3P0 is an open source JDBC data source implementation project, C3P0 depends on the jar package c3p0.jar .

XML code:

 

[html]  view plain  copy
 
  1. <bean id="dataSource" class="com.mchange.v2.c3p0.ComboPooledDataSource"         
  2.             destroy-method="close">        
  3.         <property name="driverClass" value=" oracle.jdbc.driver.OracleDriver "/>        
  4.         <property name="jdbcUrl" value="jdbc:oracle:thin:@10.1.9.171:1521:ORCL"/>        
  5.         <property name="user" value="xzzzq"/>        
  6.         <property name="password" value="xzzzq"/>        
  7.     </bean>   

 

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

    C3P0 has richer configuration properties than DBCP. Through these properties, various effective controls can be performed on the data source:
    acquireIncrement: when the connections in the connection pool are used up, the number of new connections created by C3P0 at one time;
    acquireRetryAttempts: defined in The number of repeated attempts to acquire a new connection from the database, the default is 30;
    acquireRetryDelay: the interval between two connections, in milliseconds, the default is 1000;
    autoCommitOnClose: When the connection is closed, all uncommitted operations are rolled back by default. The default is false;
    automaticTestTable: C3P0 will create an empty table named Test, and use its own query statement for testing . If this parameter is defined, the property preferredTestQuery will be ignored. You cannot perform any operations on this Test table, it will be used for C3P0 testing, and the default value is null;
    breakAfterAcquireFailure: Failure to acquire a connection will cause all threads waiting to acquire a connection to throw an exception. However, the data source remains valid and will continue to try to obtain a connection the next time getConnection() is called. If set to true, the data source will be declared disconnected and permanently closed after a failed connection attempt. The default is false;
    checkoutTimeout: When the connection pool is used up, the client calls getConnection() and waits for a new connection to be obtained. After the timeout, an SQLException will be thrown. If it is set to 0, it will wait indefinitely. The unit is milliseconds, the default is 0;
    connectionTesterClassName: Test the connection by implementing the class of ConnectionTester or QueryConnectionTester. The class name needs to be set to the fully qualified name. The default is com.mchange.v2.C3P0.impl.DefaultConnectionTester; 
    idleConnectionTestPeriod: how many seconds to check the idle connections in all connection pools, the default is 0 means no check;
    initialPoolSize: the number of connections created during initialization, which should be between minPoolSize and maxPoolSize value between. The default is 3;
    maxIdleTime: the maximum idle time, the connection that exceeds the idle time will be discarded. 0 or negative to never discard. The default is 0;
    maxPoolSize: the maximum number of connections reserved in the connection pool. The default is 15;
    maxStatements: a standard parameter of JDBC to control the number of PreparedStatements loaded in the data source. But because the pre-cached Statement belongs to a single Connection rather than the entire connection pool. So setting this parameter needs to consider many factors. If both maxStatements and maxStatementsPerConnection are 0, the cache is closed. The default is 0;
    maxStatementsPerConnection: The maximum number of cached Statements owned by a single connection in the connection pool. Defaults to 0;
    numHelperThreads: C3P0 operates asynchronously, and slow JDBC operations are done through helper processes. Extending these operations can effectively improve performance, enabling multiple operations to be executed simultaneously through multithreading. The default is 3;
    preferredTestQuery: Defines the test statement that all connection tests execute. This parameter can significantly increase the test speed in the case of using the connection test. The table under test must exist at the time of the initial data source. The default is null;
    propertyCycle: The maximum number of seconds to wait before the user modifies the system configuration parameters. The default is 300;
    testConnectionOnCheckout: Please use it only when needed due to high performance consumption. If set to true then each connection will be checked for validity when it is submitted. It is recommended to use methods such as idleConnectionTestPeriod or automaticTestTable
to improve the performance of connection tests. The default is false;
    testConnectionOnCheckin: If set to true, the validity of the connection will be checked while the connection is obtained. Defaults to false.

4. JNDI data source

    If the application is configured on a high-performance application server (such as WebLogic or Websphere, tomcat, etc.), we may prefer to use the data source provided by the application server itself. The data source of the application server uses JNDI to open the caller to use, and Spring provides the JndiObjectFactoryBean class that references JNDI resources for this purpose.

xml code:    

 

[html]  view plain  copy
 
  1. <bean id="dataSource" class="org.springframework.jndi.JndiObjectFactoryBean">        
  2.         <property name="jndiName" value="java:comp/env/jdbc/orclight"/>        
  3. </bean>  

 

 

 

[html]  view plain  copy
 
  1. <beans xmlns=http://www.springframework.org/schema/beans      
  2. xmlns:xsi=http://www.w3.org/2001/XMLSchema-instance      
  3. xmlns:jee=http://www.springframework.org/schema/jee      
  4. xsi:schemaLocation="http://www.springframework.org/schema/beans       
  5. http://www.springframework.org/schema/beans/spring-beans-2.0.xsd       
  6. http://www.springframework.org/schema/jee      
  7. http://www.springframework.org/schema/jee/spring-jee-2.0.xsd">        
  8.     <jee:jndi-lookup id="dataSource" jndi-name=" java:comp/env/jdbc/orclight"/>        
  9. </beans>  

 

5.阿里的(druid)数据源

1) 可以监控数据库访问性能,Druid内置提供了一个功能强大的StatFilter插件,能够详细统计SQL的执行性能,这对于线上分析数据库访问性能有帮助。 

2) 替换DBCPC3P0。Druid提供了一个高效、功能强大、可扩展性好的数据库连接池。 

3) 数据库密码加密。直接把数据库密码写在配置文件中,这是不好的行为,容易导致安全问题。DruidDruiver和DruidDataSource都支持PasswordCallback。 

4) SQL执行日志,Druid提供了不同的LogFilter,能够支持Common-LoggingLog4j和JdkLog,你可以按需要选择相应的LogFilter,监控你应用的数据库访问情况。 

扩展JDBC,如果你要对JDBC层有编程的需求,可以通过Druid提供的Filter-Chain机制,很方便编写JDBC层的扩展插件。 

如下是一个基于Druid内置扩展StatFilter的监控实现:

配置信息和开始三个方法一样,

xml 代码:    

 

<bean id="dataSource" class="com.alibaba.druid.pool.DruidDataSource" init-method="init" destroy-method="close">
<property name="url" value="${datasource.url}" />
<property name="username" value="${datasource.name}" />
<property name="password" value="${datasource.password}" />
<property name="connectionProperties" value="config.decrypt=true" />
<property name="filters" value="config,log4j" />
<property name="maxActive" value="${datasource.maxActive}" />
<property name="initialSize" value="${datasource.initialiSize}" />
<property name="maxWait" value="60000" />
<property name="minIdle" value="1" />
<property name="timeBetweenEvictionRunsMillis" value="60000" />
<property name="minEvictableIdleTimeMillis" value="300000" />
<property name="validationQuery" value="SELECT 'x' from dual " />
<property name="testWhileIdle" value="true" />
<property name="testOnBorrow" value="false" />
<property name="testOnReturn" value="false" />
<property name="poolPreparedStatements" value="true" />
<property name="maxPoolPreparedStatementPerConnectionSize" value="20" />
</bean>

connectionProperties:配置连接的一些属性,这里配置的config.decrypt=true,表示提供的密码是加密过的

filters:就是一个拦截器,可配置监控、日志等

maxActive:最大连接数个数

initialSize:初始化连接数个数

minIdle:空闲的连接数个数

maxWait:获取连接最大等待时间

timeBetweenEvictionRunsMillis:检测连接时间,单位毫秒

minEvictableIdleTimeMillis:检测未关闭连接大于该值则关闭连接,单位毫秒

validationQuery:系统启动时通过该sql语句验证数据库是否可用,例如oracle用SELECT 'x' from dual,mysql用SELECT 'x' 

testWhileIdle:启用空闲连接检测,以便回收

testOnBorrow:从连接池获取连接时,是否检测连接可用性,开启性能会有些许影响

testOnReturn: Whether to detect the connection availability when releasing the connection to the connection pool, the performance will be slightly affected

poolPreparedStatements: Enable psCache cache, set to true for oracle, set to false for non-oracle

maxPoolPreparedStatementPerConnectionSize: the maximum number of caches, please set it to 0 for non-oracle

Reference article:

1. Four ways to configure data sources in Spring    http://www.2cto.com/kf/201301/184061.html

2. Configure Spring data source   http://www.cnblogs.com/200911/archive/2012/08/10/2631760.html

3. Spring multi-data source configuration method   http://blog.csdn.net/nickbest85/article/details/5510466

4. How to solve the problem of multiple data sources in the spring framework    http://www.iteye.com/topic/72486

Guess you like

Origin http://10.200.1.11:23101/article/api/json?id=326858927&siteId=291194637