简体   繁体   English

检查数据库连接是否存活

[英]Check if database connection alive

I'm writing stock quotes processing engine and receiving async notifications from postgresql database with pgjdbc-ng-0.6 library.我正在编写股票报价处理引擎并使用 pgjdbc-ng-0.6 库从 postgresql 数据库接收异步通知。 I'd like to know if my database connection is still alive, so I wrote in thread's run() method我想知道我的数据库连接是否还活着,所以我在线程的run()方法中写了

    while (this.running) {
        try {
            this.running = pgConnection.isValid(Database.CONNECTION_TIMEOUT);
            Thread.sleep(10000);
        } catch (SQLException e) {
            log.warn(e.getMessage(), e);
            gracefullShutdown();
        } catch (InterruptedException e) {
            gracefullShutdown();
        }
    }

I read isValid() declaration and it stated that the function will return false if timeout reached.我阅读了isValid()声明,它指出如果超时,该函数将返回false However, isValid() just hangs indefinitely and run() is never exited.然而, isValid()只是无限期地挂起并且run()永远不会退出。 To create connectivity issues I disable VPN my application uses to connect to database.为了创建连接问题,我禁用了我的应用程序用于连接到数据库的 VPN。 Rather rude way,but function must return false... Is this bug in driver or another method exists?相当粗鲁的方式,但函数必须返回false...驱动程序中是否存在此错误或其他方法? I tried setNetworkTimeout() in PGDataSource , but without any success.我在PGDataSource尝试了setNetworkTimeout() ,但没有成功。

One of the possible handlings of this problem for Enterprise developers is to use existing threadPool to create a separate thread for submitting in Callable with test call() for DB (in case of Oracle it may be "SELECT 'OK' FROM dual" ), using statement object.execute('...') , (not executeUpdate , because it may cause the call to get stuck), and further using for example - future.get(3, TimeUnit.Seconds) .对于企业开发人员来说,解决这个问题的一种可能方法是使用现有的 threadPool 创建一个单独的线程,用于在 Callable 中提交,并带有 test call() for DB(在 Oracle 的情况下,它可能是"SELECT 'OK' FROM dual" ),使用语句object.execute('...') ,(不是executeUpdate ,因为它可能导致调用卡住),并进一步使用例如 - future.get(3, TimeUnit.Seconds)

Using this approach in a final call you need to catch InterruptedException for get() call.在最后一次调用中使用这种方法,您需要为get()调用捕获InterruptedException If Callable throws you set database availability as false, if not then true.如果 Callable 抛出您将数据库可用性设置为 false,否则为 true。

Before using this approach inside the Enterprise application you have to ensure you have access to application server threadPool executor in certain object and @Autowire it there.在企业应用程序中使用这种方法之前,您必须确保您可以访问某个对象中的应用程序服务器 threadPool 执行程序,并在那里 @Autowire 它。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM