休眠检查线程中与数据库的连接(每个时间段) [英] Hibernate check connection to database in Thread ( every time period )

查看:77
本文介绍了休眠检查线程中与数据库的连接(每个时间段)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

什么是监视数据库连接的最佳/良好/最佳方式。
我正在编写秋千应用程序。我要它做的是在每个时间段检查与数据库的连接。我已经尝试过类似的事情。

What is best/good/optimal way to monitor connection to database. Im writing swing application. What I want it to do is to check connection with database every time period. I've tried something like this.

org.hibernate.Session session = null;
            try {
                System.out.println("Check seesion!");
                session = HibernateUtil.getSessionFactory().openSession();

            } catch (HibernateException ex) {
            } finally {
                session.close();
            }

但这没用。
我想到的第二个问题是此会话关闭将如何影响其他查询。

But that dosn't work. Second question which is comming to my mind is how this session closing will affect other queries.

推荐答案

使用连接像c3p0 。您可以将此类池配置为监视池中的连接-在将连接传递给Hibernate之前,将其返回或定期接收之后。如果连接断开,则池会透明地关闭它,丢弃并打开一个新连接-无需您注意。

Use a connection pool like c3p0 or dbcp. You can configure such pool to monitor connections in pool - before passing connection to Hibernate, after receiving it back or periodically. If the connection is broken, the pool with transparently close it, discard and open a new one - without you noticing.

数据库连接池更适合多用户使用,数据库密集型应用程序,可以同时打开多个连接,但是我认为这并不过分。绑定到最大1个连接的池应该可以正常工作。

Database connection pools are better suited for multi-user, database heavy application where several connections are opened at the same time, but I don't think it's an overkill. Pools should work just fine being bound to max 1 connection.

更新:每次尝试访问数据库时,Hibernate都会询问 DataSource (连接池)。如果没有可用的活动连接(例如,由于数据库关闭),这将引发异常。如果您想提前知道数据库何时不可用(即使用户什么都不做),那么很不幸,您需要偶尔执行一次后台线程检查数据库。

UPDATE: every time you try to access the database Hibernate will ask the DataSource (connection pool). If no active connection is available (e.g. because database is down), this will throw an exception. If you want to know in advance when database is unavailable (even when user is not doing anything), unfortunately you need a background thread checking the database once in a while.

但是,在某些配置中,仅打开会话可能还不够。最好运行一些虚拟的廉价查询,例如 SELECT 1 (在原始JDBC中)。

However barely opening a session might not be enough in some configurations. You'll better run some dummy, cheap query like SELECT 1 (in raw JDBC).

这篇关于休眠检查线程中与数据库的连接(每个时间段)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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