问题:
    系统采用Spring MVC 2.5 + Spring 2.5 + Hibernate 3.2架构,其中数据源连接池采用的是Apache commons DBCP。问题是这样的,系统运行一段时间后(大致每隔8小时),访问系统会出现如下错误,再次访问恢复正常。

org.springframework.web.util.NestedServletException: Request processing failed; nested exception is org.hibernate.exception.GenericJDBCException: Cannot release connection
 at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:583)
 at org.springframework.web.servlet.FrameworkServlet.doGet(FrameworkServlet.java:501)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:617)
 at javax.servlet.http.HttpServlet.service(HttpServlet.java:717)
 at org.apache.catalina.core.ApplicationFilterChain.internalDoFilter(ApplicationFilterChain.java:290)
 at org.apache.catalina.core.ApplicationFilterChain.doFilter(ApplicationFilterChain.java:206)

Caused by: org.hibernate.exception.GenericJDBCException: Cannot release connection
 at org.hibernate.exception.SQLStateConverter.handledNonSpecificException(SQLStateConverter.java:103)
 at org.hibernate.exception.SQLStateConverter.convert(SQLStateConverter.java:91)
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:43)
 at org.hibernate.exception.JDBCExceptionHelper.convert(JDBCExceptionHelper.java:29)
 at org.hibernate.jdbc.ConnectionManager.closeConnection(ConnectionManager.java:449)
 at org.hibernate.jdbc.ConnectionManager.cleanup(ConnectionManager.java:379)
 at org.hibernate.jdbc.ConnectionManager.manualDisconnect(ConnectionManager.java:333)
 at org.hibernate.impl.SessionImpl.disconnect(SessionImpl.java:375)
 at org.springframework.orm.hibernate3.HibernateTransactionManager.doCleanupAfterCompletion(HibernateTransactionManager.java:744)
 at org.springframework.transaction.support.AbstractPlatformTransactionManager.cleanupAfterCompletion(AbstractPlatformTransactionManager.java:989)
 at org.springframework.transaction.support.AbstractPlatformTransactionManager.processRollback(AbstractPlatformTransactionManager.java:855)
 at org.springframework.transaction.support.AbstractPlatformTransactionManager.rollback(AbstractPlatformTransactionManager.java:800)
 at org.springframework.transaction.interceptor.TransactionAspectSupport.completeTransactionAfterThrowing(TransactionAspectSupport.java:339)
 at org.springframework.transaction.interceptor.TransactionInterceptor.invoke(TransactionInterceptor.java:110)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
 at org.springframework.aop.interceptor.ExposeInvocationInterceptor.invoke(ExposeInvocationInterceptor.java:89)
 at org.springframework.aop.framework.ReflectiveMethodInvocation.proceed(ReflectiveMethodInvocation.java:171)
 at org.springframework.aop.framework.Cglib2AopProxy$DynamicAdvisedInterceptor.intercept(Cglib2AopProxy.java:635)
 at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
 at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:39)
 at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:25)
 at java.lang.reflect.Method.invoke(Method.java:585)
 at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.doInvokeMethod(HandlerMethodInvoker.java:421)
 at org.springframework.web.bind.annotation.support.HandlerMethodInvoker.invokeHandlerMethod(HandlerMethodInvoker.java:136)
 at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.invokeHandlerMethod(AnnotationMethodHandlerAdapter.java:326)
 at org.springframework.web.servlet.mvc.annotation.AnnotationMethodHandlerAdapter.handle(AnnotationMethodHandlerAdapter.java:313)
 at org.springframework.web.servlet.DispatcherServlet.doDispatch(DispatcherServlet.java:875)
 at org.springframework.web.servlet.DispatcherServlet.doService(DispatcherServlet.java:807)
 at org.springframework.web.servlet.FrameworkServlet.processRequest(FrameworkServlet.java:571)
  36 more
Caused by: java.sql.SQLException: Already closed.
 at org.apache.commons.dbcp.PoolableConnection.close(PoolableConnection.java:77)
 at org.apache.commons.dbcp.PoolingDataSource$PoolGuardConnectionWrapper.close(PoolingDataSource.java:180)
 at org.springframework.orm.hibernate3.LocalDataSourceConnectionProvider.closeConnection(LocalDataSourceConnectionProvider.java:96)
 at org.hibernate.jdbc.ConnectionManager.closeConnection(ConnectionManager.java:445)
  62 more

解决:
    造成Cannot release connection的原因有很多,要具体问题具体分析。从异常分析,造成这个异常 org.hibernate.exception.GenericJDBCException: Cannot release connection 归根结底是Caused by: java.sql.SQLException: Already closed. 即连接已关闭。所以解决的办法就要从DBCP的参数配置入手,见下面的参数配置properties文件。

#### :: Apache DBCP :: ####
jdbc.driverClassName=oracle.jdbc.driver.OracleDriver
jdbc.url=jdbc:oracle:thin:@10.165.153.9:1521:PRDC
jdbc.username=guser
jdbc.password=guser
#初始化连接
jdbc.initialSize=0
#连接池的最大活动个数
jdbc.maxActive=20
#没有人用连接的时候,最大闲置的连接个数。
jdbc.maxIdle=100
#没有人用连接的时候,最小闲置的连接个数。
jdbc.minIdle=0
#超时等待时间以毫秒为单位
jdbc.maxWait=10000
#是否自动回收超时连接
jdbc.removeAbandoned=true
#设置被遗弃的连接的超时的时间(以秒数为单位),即当一个连接被遗弃的时间超过设置的时间,则它会自动转换成可利用的连接。默认的超时时间是300秒。
jdbc.removeAbandonedTimeout=60
#是否在自动回收超时连接的时候打印连接的超时错误
jdbc.logAbandoned = true
#给出一条简单的sql语句进行验证
jdbc.validationQuery=select 1 from dual
#在取出连接时进行有效验证
jdbc.testOnBorrow=true

其中标红的两个参数的作用是对池化连接进行验证,This will ensure that DBCP only hands out good connections to Hibernate. 故加上这两个参数后,这个异常就不会再出现了。在Spring中指定数据源如下:

<!-- 數據源定義 使用Apache DBCP連接池 -->
    <bean id="dataSource" class="org.apache.commons.dbcp.BasicDataSource" destroy-method="close">
        <property name="driverClassName" value="${jdbc.driverClassName}" />
        <property name="url" value="${jdbc.url}" />
        <property name="username" value="${jdbc.username}" />
        <property name="password" value="${jdbc.password}" />
        <property name="maxActive" value="${jdbc.maxActive}" />
        <property name="maxIdle" value="${jdbc.maxIdle}" />
        <property name="maxWait" value="${jdbc.maxWait}" />
        <property name="removeAbandoned" value="${jdbc.removeAbandoned}" />
        <property name="removeAbandonedTimeout" value="${jdbc.removeAbandonedTimeout}" />
        <property name="logAbandoned" value="${jdbc.logAbandoned}" />
        <property name="validationQuery" value="${jdbc.validationQuery}" />
        <property name="testOnBorrow" value="${jdbc.testOnBorrow}" />
    </bean>

问题解决了。

另附

DBCP参数详细说明(部分参考了 http://justin-ray.javaeye.com/blog/413591 ):

在配置时,大部分参数一目了然,不再赘述,有不清楚的话,可以参考下面的详细说明。主要难以理解的参数主要有:removeAbandoned 、logAbandoned、removeAbandonedTimeout、maxWait这四个参数,设置了rmoveAbandoned=true那么在getNumActive()快要到getMaxActive()的时候,系统会进行无效的Connection的回收,回收的Connection为removeAbandonedTimeout(默认300秒)中设置的秒数后没有使用的Connection,激活回收机制大致为getNumActive()=getMaxActive()-3。logAbandoned=true的话,将会在回收事件后,在log中打印出回收Connection的错误信息,包括在哪个地方用了Connection却忘记关闭了,在调试的时候很有用。在这里个人建议maxWait的时间不要设得太长,maxWait如果设置太长那么客户端会等待很久才激发回收事件。

Parameters


Parameter Description
username The connection username to be passed to our JDBC driver to establish a connection.
password The connection password to be passed to our JDBC driver to establish a connection.
url The connection URL to be passed to our JDBC driver to establish a connection.
driverClassName The fully qualified Java class name of the JDBC driver to be used.
connectionProperties The connection properties that will be sent to our JDBC driver when establishing new connections. 
Format of the string must be [propertyName=property;]* 
NOTE - The "user" and "password" properties will be passed explicitly, so they do not need to be included here.

Parameter Default Description
defaultAutoCommit true The default auto-commit state of connections created by this pool.
defaultReadOnly driver default The default read-only state of connections created by this pool. If not set then the setReadOnly method will not be called. (Some drivers don't support read only mode, ex: Informix)
defaultTransactionIsolation driver default The default TransactionIsolation state of connections created by this pool. One of the following: (see javadoc)

  • NONE
  • READ_COMMITTED
  • READ_UNCOMMITTED
  • REPEATABLE_READ
  • SERIALIZABLE
defaultCatalog   The default catalog of connections created by this pool.

Parameter Default Description
initialSize 0 The initial number of connections that are created when the pool is started. 
Since: 1.2
maxActive 8 The maximum number of active connections that can be allocated from this pool at the same time, or negative for no limit.
maxIdle 8 The maximum number of connections that can remain idle in the pool, without extra ones being released, or negative for no limit.
minIdle 0 The minimum number of connections that can remain idle in the pool, without extra ones being created, or zero to create none.
maxWait indefinitely The maximum number of milliseconds that the pool will wait (when there are no available connections) for a connection to be returned before throwing an exception, or -1 to wait indefinitely.

NOTE: If maxIdle is set too low on heavily loaded systems it is possible you will see connections being closed and almost immediately new connections being opened. This is a result of the active threads momentarily closing connections faster than they are opening them, causing the number of idle connections to rise above maxIdle. The best value for maxIdle for heavily loaded system will vary but the default is a good starting point.


Parameter Default Description
validationQuery   The SQL query that will be used to validate connections from this pool before returning them to the caller. If specified, this query MUST be an SQL SELECT statement that returns at least one row.
testOnBorrow true The indication of whether objects will be validated before being borrowed from the pool. If the object fails to validate, it will be dropped from the pool, and we will attempt to borrow another.
NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
testOnReturn false The indication of whether objects will be validated before being returned to the pool. 
NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
testWhileIdle false The indication of whether objects will be validated by the idle object evictor (if any). If an object fails to validate, it will be dropped from the pool. 
NOTE - for a true value to have any effect, the validationQuery parameter must be set to a non-null string.
timeBetweenEvictionRunsMillis -1 The number of milliseconds to sleep between runs of the idle object evictor thread. When non-positive, no idle object evictor thread will be run.
numTestsPerEvictionRun 3 The number of objects to examine during each run of the idle object evictor thread (if any).
minEvictableIdleTimeMillis 1000 * 60 * 30 The minimum amount of time an object may sit idle in the pool before it is eligable for eviction by the idle object evictor (if any).
connectionInitSqls null A Collection of SQL statements that will be used to initialize physical connections when they are first created. These statements are executed only once - when the configured connection factory creates the connection.

Parameter Default Description
poolPreparedStatements false Enable prepared statement pooling for this pool.
maxOpenPreparedStatements unlimited The maximum number of open statements that can be allocated from the statement pool at the same time, or zero for no limit.

 This component has also the ability to pool PreparedStatements. When enabled a statement pool will be created for each Connection and PreparedStatements created by one of the following methods will be pooled:

  • public PreparedStatement prepareStatement(String sql)
  • public PreparedStatement prepareStatement(String sql, int resultSetType, int resultSetConcurrency)

NOTE - Make sure your connection has some resources left for the other statements. Pooling PreparedStatements may keep their cursors open in the database, causing a connection to run out of cursors, especially if maxOpenPreparedStatements is left at the default (unlimited) and an application opens a large number of different PreparedStatements per connection. To avoid this problem, maxOpenPreparedStatements should be set to a value less than the maximum number of cursors that can be open on a Connection.


Parameter Default Description
accessToUnderlyingConnectionAllowed false Controls if the PoolGuard allows access to the underlying connection.

When allowed you can access the underlying connection using the following construct:

    Connection conn = ds.getConnection();
Connection dconn = ((DelegatingConnection) conn).getInnermostDelegate();
...
conn.close()

 Default is false, it is a potential dangerous operation and misbehaving programs can do harmfull things. (closing the underlying or continue using it when the guarded connection is already closed) Be carefull and only use when you need direct access to driver specific extentions.

NOTE: Do not close the underlying connection, only the original one.


Parameter Default Description
removeAbandoned false Flag to remove abandoned connections if they exceed the removeAbandonedTimout.
If set to true a connection is considered abandoned and eligible for removal if it has been idle longer than the removeAbandonedTimeout. Setting this to true can recover db connections from poorly written applications which fail to close a connection.
removeAbandonedTimeout 300 Timeout in seconds before an abandoned connection can be removed.
logAbandoned false Flag to log stack traces for application code which abandoned a Statement or Connection.
Logging of abandoned Statements and Connections adds overhead for every Connection open or new Statement because a stack trace has to be generated.

 If you have enabled "removeAbandoned" then it is possible that a connection is reclaimed by the pool because it is considered to be abandoned. This mechanism is triggered when (getNumIdle() < 2) and (getNumActive() > getMaxActive() - 3)

 For example maxActive=20 and 18 active connections and 1 idle connection would trigger the "removeAbandoned". But only the active connections that aren't used for more then "removeAbandonedTimeout" seconds are removed, default (300 sec). Traversing a resultset doesn't count as being used.

Hibernate Cannot release connection 了,有办法解决!的更多相关文章

  1. fatal: read error: Connection reset by peer解决办法

    标签(空格分隔): ceph源码安装,git 问题描述: 源码安装ceph,克隆代码时提示如下错误: [root@localhost ~]# git clone git://github.com/ce ...

  2. 170106、用9种办法解决 JS 闭包经典面试题之 for 循环取 i

    闭包 1.正确的说,应该是指一个闭包域,每当声明了一个函数,它就产生了一个闭包域(可以解释为每个函数都有自己的函数栈),每个闭包域(Function 对象)都有一个 function scope(不是 ...

  3. Hibernate Session 获取connection

    Hibernate Session 获取connection 由于最近一个项目要用到一条辅助的SQL ,hibernate里面的SQLQuery API 总的SQL语句不能包含 : 冒号, 固放弃Hi ...

  4. [转]Hibernate中property-ref的应用,常用来解决遗留数据库One To Many关系

    [转]Hibernate中property-ref的使用,常用来解决遗留数据库One To Many关系 1.如表Class(ClassID,Class_No,ClassName)与Student(S ...

  5. 用9种办法解决 JS 闭包经典面试题之 for 循环取 i

    2017-01-06 Tomson JavaScript 转自 https://segmentfault.com/a/1190000003818163 闭包 1.正确的说,应该是指一个闭包域,每当声明 ...

  6. cassandra运行出现了Unable to gossip with any seeds,cqlsh链接不上,提示connection refused处理办法

    cassandra运行出现了Unable to gossip with any seeds,cqlsh链接不上,提示connection refused处理办法 问题描述 当启动了cassandra之 ...

  7. Hibernate的懒加载session丢失解决方法

    在web.xml加入spring提供的过滤器,延长session的生命周期 <!--Hibernate的懒加载session丢失解决方法 --> <filter> <fi ...

  8. 最快速的办法解决MySQL数据量增大之后翻页慢问题

    MySQL最易碰到的性能问题就是数据量逐步增大之后的翻页速度变慢的额问题,而且越往后翻页速度越慢,如果用最快速的办法解决,以下就是解决办法,简单方便. 1.问题现状 现有MySQL数据表 event_ ...

  9. struts,hibernate,spring配置时问题汇总及解决办法

    1.java.lang.NoClassDefFoundError: org/objectweb/asm/ClassVisitor 缺少asm-3.3.jar 2.java.lang.NoClassDe ...

随机推荐

  1. opencv颜色提取color filting

    # -*- coding: utf-8 -* import numpy as np import cv2 cap = cv2.VideoCapture(0) while True: _ , frame ...

  2. IOS-每个程序员的编程之路上都应该看这11本书

    国外知名网站stackoverflow上有一个问题调查: 哪本书是对程序员最有影响.每个程序员都该阅读的书?,这个调查已历时两年,目前为止吸引了153,432人访问,读者共推荐出了478本书(还在增加 ...

  3. SQL语句往Oracle数据库中插入日期型数据(to_date的用法)

    Oracle 在操作数据库上相比于其他的 T-sql 有微小的差别,但是在插入时间类型的数据是必须要注意他的 to_date 方法,具体的情况如下: --SQL语句往Oracle数据库中插入日期型数据 ...

  4. c#批量上传图片到服务器示例分享

    这篇文章主要介绍了c#批量上传图片到服务器示例,服务器端需要设置图片存储的虚拟目录,需要的朋友可以参考下 /// <summary> /// 批量上传图片 /// </summary ...

  5. MySQL Batched Key Access

    Batched Key Access是MySQL 5.6 版本中的新特性,是一种用户提高表join性能的算法.[Batched Key Access]       对于多表join语句,当MySQL使 ...

  6. *SCM-MANAGER独立部署方式

    从官网获取最新版本 scm-manager 独立安装包 https://www.scm-manager.org/download/ 解压 为合适的路径 修改 services.bat 文件服务相关信息 ...

  7. vue.js 源代码学习笔记 ----- 工具方法 error

    import config from '../config' import { warn } from './debug' import { inBrowser } from './env' // 这 ...

  8. JQ上传预览+存数据库

    因为之前老师讲的方法有不少BUG 现在经过完善已经修复 之前老是讲的方法是每一张都会被传到后台文件夹里面去 导致在预览过程中如果刷新页面 那么预览的图片不能从后台文件夹中删除  这个方法实现在本地预览 ...

  9. 我的第一个React自定义组件

    今天随便翻了一下antd的组件库,看到下面这样的组件,当时我就震惊了: 这尼玛,这是出于什么样的考虑,一个列表还要用户编写子项的渲染方式. 所以,我就自己写了一个 List.js: List.less ...

  10. 创建你的第一个Flutter应用程序

    前言 Flutter,Google推出的跨平台开发框架.就在前几天,Flutter的首个发布预览版(Release Preview 1)正式发布! 即将迎来Flutter 正式版(1.0).本篇将带你 ...