如何防止 Hibernate + c3p0 + MySql 创建大量休眠连接? [英] How can I prevent Hibernate + c3p0 + MySql creating large numbers of sleeping connections?

查看:22
本文介绍了如何防止 Hibernate + c3p0 + MySql 创建大量休眠连接?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我将 GWT 与 Hibernate、c3p0 和 MySQL 结合使用,以生成受众有限(每天最多 50 个用户)的网络应用程序.在测试期间,我发现 Hibernate 会打开与每个会话的连接,但不会关闭它,无论是否使用 close() 方法.

I'm using GWT with Hibernate, c3p0 and MySQL to produce a web app with a limited audience (max 50 users per day). During testing I found that Hibernate was opening a connection with each session but not closing it, irrespective of use of the close() method.

我目前的配置如下:

hibernate.connection.driver_class=com.mysql.jdbc.Driver
hibernate.connection.url=
hibernate.connection.username=
hibernate.connection.password=
hibernate.dialect=org.hibernate.dialect.MySQLDialect
hibernate.current_session_context_class=thread
hibernate.c3p0.min_size=1
hibernate.c3p0.max_size=1
hibernate.c3p0.timeout=10
hibernate.c3p0.max_statements=50
hibernate.c3p0.idle_test_period=10
hibernate.c3p0.unreturned_connection_timeout=1
hibernate.connection.provider_class=org.hibernate.connection.C3P0ConnectionProvider

每次与应用程序的新连接都会创建一个新池.例如,如果我将池大小设置为 3,则应用程序的 2 个连接将导致 6 个连接,直到应用程序关闭.

With each new connection to the application a new pool is created. For example if I set the pool size to 3, 2 connections to the application result in 6 connections until the application is closed.

预期行为是在每次事务后简单地关闭或重用连接.我怎样才能做到这一点?

The intended behaviour is to simply close or reuse the connections after each transaction. How can I achieve this?

推荐答案

在测试过程中,我发现 Hibernate 会打开与每个会话的连接,但不会关闭它,而不管使用 close() 方法

During testing I found that Hibernate was opening a connection with each session but not closing it, irrespective of use of the close() method

使用连接池时,调用 Connection#close() 不会物理关闭连接,而是将其返回到连接池以备将来重用.换句话说,连接保持打开状态,这就是使用池的全部意义所在.

When using a connection pool, calling Connection#close() doesn't physically close the connection but return it to the pool for future reuse. In other words, the connection stays open and that's the whole point of using a pool.

我调用以下内容:AnnotationConfiguration().buildSessionFactory().getCurrentSession();

I call the following: AnnotationConfiguration().buildSessionFactory().getCurrentSession();

嗯,这就是问题所在.您一遍又一遍地创建 SessionFactory(每个创建自己的池),而您应该在应用程序的生命周期内只创建一次.如果您没有使用任何特定的框架,这通常是在某个实用程序类(著名的 HibernateUtil 类)中完成的.

Well, that's the problem. You are creating a SessionFactory over and over (each creating its own pool) while you should create it only once for the lifetime of your application. If you are not using any particular framework, this is typically done in some utility class (the famous HibernateUtil class).

官方 Hibernate Tutorial 有一个这种类的非常基本的例子.或者查看这个,内容更丰富一些.

The official Hibernate Tutorial has a very basic example of such a class. Or see this one which is a bit richer.

这篇关于如何防止 Hibernate + c3p0 + MySql 创建大量休眠连接?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆