Hibernate使用了很多线程 [英] Hibernate usage with a lot of threads

查看:141
本文介绍了Hibernate使用了很多线程的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的独立应用程序中,单次生成超过1000个线程,每个线程都有自己的Hibernate会话。但是在这种情况下,会话的计数超过了数据库最大连接限制,这会引发错误。



我尝试设置 .getCurrentSession() 而不是 .openSession(),但它没有效果,因为Hibernate为每个新线程打开新的自己的会话。 b
$ b

我该如何解决这个问题?我能以某种方式设置并发连接的插槽数吗?对于例如传递100个连接,并让另一个900等到这100个关闭以进一步处理?帮助解决这个问题。



这是一篇关于设置连接池的文章


大多数人使用连接池,如C3P0,可用于
,确保会话重用并加速您的代码。



我使用的最佳结构是在
应用程序启动时创建SessionFactory,因为这会将连接池设置为
数据库。然后,利用可能的单例模式来保存单个
SessionFactory,为每个从单个SessionFactory执行
的事务请求新会话。 Hibernate将利用底层的
连接池来处理会话重用,以加快速度和优化。

这是另一篇关于各种连接的文章pooling libraries available。


默认情况下,Hibernate具有获取数据源
实现的能力(javax.sql.DataSource )通过适当地设置
属性从JNDI中获得


hibernate默认连接池


In my standalone app, generating over 1000 threads in single time and each thread has it's own Hibernate session. But in this case, count of sessions hits over database max connections restriction that throws an error.

I've tried to set .getCurrentSession() instead of .openSession(), but it brought no effect, because Hibernate opens new own session for each new thread anyway.

How can i round this problem? Can i set somehow the count of slots for concurrent connections? For e.g. pass 100 connections and let another 900 to wait till these 100 will be closed to process this further?

解决方案

Using a connection pool can help solve this.

Here is a post about setting up a connection pool Can you only have one hibernate session per thread in java?

Most people utilize a connection pool, like C3P0 that can be used to ensure session reuse and speed up your code.

The best structure I use is to create a SessionFactory once in application launch, as this sets up the connection pool to the database. Then, utilizing maybe a singleton pattern to keep a single SessionFactory, request new sessions for each transaction you perform from the single SessionFactory. Hibernate will utilize the underlying connection pool to handle session reuse for speed and optimization.

Here is another post on various connection pooling libraries available.

By default, Hibernate ships with the ability to obtain a data source implementation ( javax.sql.DataSource ) from JNDI by setting the properties appropriately

hibernate default connection pooling

这篇关于Hibernate使用了很多线程的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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