[英]Grails groovy too many hibernate connections
我在手动进行交易管理方面很挣扎。 背景:我需要运行运行批处理的quarz crons。 建议批处理手动决定何时刷新到数据库,以免降低应用程序的速度。
我有一个池休眠连接,如下所示
dataSource {
pooled = true
driverClassName = "com.mysql.jdbc.Driver"
dialect = "org.hibernate.dialect.MySQL5InnoDBDialect"
properties {
maxActive = 50
maxIdle = 25
minIdle = 1
initialSize = 1
minEvictableIdleTimeMillis = 60000
timeBetweenEvictionRunsMillis = 60000
numTestsPerEvictionRun = 3
maxWait = 10000
testOnBorrow = true
testWhileIdle = true
testOnReturn = false
validationQuery = "SELECT 1"
validationQueryTimeout = 3
validationInterval = 15000
jmxEnabled = true
maxAge = 10 * 60000
// http://tomcat.apache.org/tomcat-7.0-doc/jdbc-pool.html#JDBC_interceptors
jdbcInterceptors = "ConnectionState;StatementCache(max=200)"
}
}
hibernate {
cache.use_second_level_cache = false
cache.use_query_cache = false
cache.region.factory_class = 'net.sf.ehcache.hibernate.EhCacheRegionFactory'
show_sql = false
logSql = false
}
cron作业会在我运行的服务中调用服务,请执行以下操作:
for(int g=0; g<checkResults.size() ;g++) {
def tmpSearchTerm = SearchTerm.findById((int)results[g+i][0])
tmpSearchTerm.count=((String)checkResults[g]).toInteger()
batch.add(tmpSearchTerm)
}
//increase counter
i+=requestSizeTMP
if (i%(requestSize*4)==0 || i+1==results.size()){
println "PREPARATION TO WRITE:" + i
SearchTerm.withSession{
def tx = session.beginTransaction()
for (SearchTerm s: batch) {
s.save()
}
batch.clear()
tx.commit()
println ">>>>>>>>>>>>>>>>>>>>>writing: ${i}<<<<<<<<<<<<<<<<<<<<<<"
}
session.flush()
session.clear()
}
}
所以我将东西添加到批处理中,直到我有足够的东西(请求大小或最后一项的4倍),然后尝试将其写入数据库。
一切正常..但是,代码似乎以某种方式打开了休眠事务,并且没有关闭它们。 我真的不明白为什么,但是我遇到了一个严重的错误,tomcat在连接过多时崩溃。 我有2个问题,我不明白:
1)如果dataSource被池化并且maxActive为50,如果tomcat的限制为500,我怎么会得到太多连接错误。
2)我如何显式终止交易,以使我没有那么多打开的连接?
您可以使用withTransaction
因为它将管理事务。
例如
Account.withTransaction { status ->
def source = Account.get(params.from)
def dest = Account.get(params.to)
int amount = params.amount.toInteger()
if (source.active) {
source.balance -= amount
if (dest.active) {
dest.amount += amount
}
else {
status.setRollbackOnly()
}
}
}
您可以在http://grails.org/doc/latest/ref/Domain%20Classes/withTransaction.html中查看withTransaction
您可以在https://stackoverflow.com/a/19692615/1610918中看到withSession和withTransaction之间的区别
------更新-----------
但是我希望您使用服务,并且可以从工作中调用它。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.