日期:2014-05-16  浏览次数:20393 次

spring + hibernate + c3p0 数据库连接用完问题排查

项目中操作数据库一般会用连接池以c3p0为例, hibernate事务管理一般交spring并使用aop实现如下:

	<bean id="transactionManager"
		class="org.springframework.orm.hibernate3.HibernateTransactionManager">
		<property name="sessionFactory" ref="sessionFactory">
		</property>
	</bean>
	<tx:advice id="transaction" transaction-manager="transactionManager">
		<tx:attributes>
			<tx:method name="*" propagation="REQUIRED" />
		</tx:attributes>
	</tx:advice>

	<bean id="logger" class="com.yj.tr.gds.log.MethodLogger"></bean>
	<aop:config>
		<!-- pointcuts -->
		<aop:pointcut id="api"
			expression="execution(public * com.xxx.api.impl.*.*(..))" />
		<!-- transaction advisors -->
		<aop:advisor advice-ref="transaction" pointcut-ref="api" />
	</aop:config>

这样spring就给我们管理com.xxx.api.impl包下所有公共方法的事务

但是这样配置的时候我们可能会忘记或漏掉一些需要配置事务的方法,比如 :com.yyy.api.impl包下所有类方法都有操作数据库 如果没有配置

<aop:pointcut id="api"
			expression="execution(public * com.yyy.api.impl.*.*(..))" />
		<!-- transaction advisors -->
		<aop:advisor advice-ref="transaction" pointcut-ref="api2" />

的话 当调用此包下方法的时候数据库连接很快就会消耗完了


问题排查方法

1. 给所有操作数据库的方法加上log

2.c3p0的log级别设置为debug

这样log里会看到像这样的信息:

incremented pending_acquires: 1 --[DEBUG] 2013-02-19 00:03:07
about to close PreparedStatement (open PreparedStatements: 1, globally: 1) --[DEBUG] 2013-02-19 00:03:07
acquire test -- pool size: 91; target_pool_size: 92; desired target? 92 --[DEBUG] 2013-02-19 00:03:07
incremented pending_acquires: 2 --[DEBUG] 2013-02-19 00:03:07

如果poolsize超过了我们设置的最大连接数(maxPoolSize),查看第一次出现这此信息的前面调用了哪些方法,再一一校对是不是方法上没有加事务控制