无法打开新连接,因为现有连接仍在当前线程上-ActiveJDBC [英] Cannot open a new connection because existing connection is still on current thread - ActiveJDBC

查看:262
本文介绍了无法打开新连接,因为现有连接仍在当前线程上-ActiveJDBC的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

一段时间后,我收到此错误Cannot open a new connection because existing connection is still on current thread.我认为该错误很容易解释.我的代码是这样的:

I'm getting this error Cannot open a new connection because existing connection is still on current thread after a while. I think the error is pretty self explanatory. My code is this:

String mySQLUrl ="jdbc:postgresql://" + dataLayer.PostgreSQL_Host +"/" + dataLayer.PostgreSQL_Database;

String mySQLUrl = "jdbc:postgresql://" + dataLayer.PostgreSQL_Host + "/" + dataLayer.PostgreSQL_Database;

Base.open("org.postgresql.Driver",mySQLUrl,dataLayer.getPostgreSQLUser(),dataLayer.getPostgreSQLPassword());

Base.open("org.postgresql.Driver", mySQLUrl, dataLayer.getPostgreSQLUser(), dataLayer.getPostgreSQLPassword());

为了避免该错误,我想创建一个连接工厂,但是要实现这一点,我需要知道如何验证是否打开了一个连接(并且仍然有效)并返回它,否则,请创建它.是否有内置的东西或我应该使用旧的尝试捕获器? :|

In order to avoid that error, i would like to create a connection factory, but to accomplish this, i need to know how to verify if there's a connection opened (and still valid) and return it, otherwise, create it. Is there something built or should i use the good old try-catch? :|

推荐答案

如果遇到此异常,则意味着在打开新线程时,当前线程上仍具有连接.这种类型的代码可能会导致连接泄漏,因此该框架阻止您这样做.

If you are getting this exception, then that means that you still have a connection on the current Thread while opening a new one. This type of code may lead to a connection leak, so the framework prevents you from doing so.

此页面: http://javalite.io/database_connection_management#thread-connection-propagation 解释模型在当前线程上找到连接.

由于您没有为您的应用程序提供任何上下文,因此我将举几个示例.

Since you are not providing any context for your application, I will give you a couple of examples.

如果这是批处理应用程序(独立应用程序),则需要打开一个连接,使用它然后关闭:

If this is a batch application (standalone app), you need to open a connection, use it then close:

try(DB db = Base.open(...)){

  // your code here
}

这将确保连接已关闭并从当前线程中删除. 如果使用的是ActiveWeb,则可以使用DBConnectionFilter: http://javalite.io/database_configuration 像在任何Web应用程序中一样,您将在处理请求之前打开一个连接(从连接池中拉出),在控制器,然后在请求结束时关闭连接(返回到池).

This will ensure that the connection is closed and removed from a current thread. If you are using ActiveWeb, then you can use the DBConnectionFilter: http://javalite.io/database_configuration As in any web app, you would open a connection (pull from the connection pool) before a request is processed, use the connection in your controller, then close a connection (return to pool) at the end of a request.

如果您不使用ActiveWeb,则可以编写一个简单的Servlet过滤器来完成此操作,这是一个示例:

If you are not using ActiveWeb, you can write a simple Servlet Filter that will do the same, here is one example: ActiveJdbcFilter

这篇关于无法打开新连接,因为现有连接仍在当前线程上-ActiveJDBC的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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