java 将连接对象返回到 HikariCP 池的最佳方法
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/25367261/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Best approach for returning connection objects to HikariCP pool
提问by Ordous
I am trying to use HikariCP connection pool. I was able to get it to work and get a connection that I could use. I am not sure what is the best approach for returning the connection to the pool.
我正在尝试使用 HikariCP 连接池。我能够让它工作并获得我可以使用的连接。我不确定将连接返回到池的最佳方法是什么。
I have the following questions:
我有以下问题:
- Should I close the connection when I am done, rely on idleTimeoutand maxLifetimesettings or is there another call that I can use so as not to hog the connections from the pool?
- If I close the connections (instead of returning to the pool), would that not result in additional connection objects being created to meet the requirements of the connection poolsize?
- 我应该在完成后关闭连接,依赖idleTimeout和maxLifetime设置还是有另一个我可以使用的调用,以免从池中占用连接?
- 如果我关闭连接(而不是返回到池中),会不会导致创建额外的连接对象以满足连接池大小的要求?
Looking for helpful suggestions.
寻找有用的建议。
回答by Ordous
As with most connection pools, Hikari doesn't give you an actual JDBC Connection when you ask for one. What it does instead is give you a proxy that implements the Connection
interface. In the case of Hikari - it's a ConnectionProxy
object.
与大多数连接池一样,当您要求时,Hikari 不会为您提供实际的 JDBC 连接。它的作用是为您提供一个实现该Connection
接口的代理。在 Hikari 的情况下 - 它是一个ConnectionProxy
对象。
This proxy serves a few purposes, the main of which is - take the control of opening/closing connections and statements away from you and into the connection pool. This happens automagically and you should be using your connections as usual. This includes closing them after use.
这个代理有几个目的,其中主要是 - 控制打开/关闭连接和语句,远离你进入连接池。这会自动发生,您应该像往常一样使用您的连接。这包括在使用后关闭它们。
If you look at the source code for Hikari, at the ConnectionProxy
class in particular, you will see that the close()
method is very different from the standard one. The code reads as:
如果你看一下对阿光的源代码,在ConnectionProxy
特别班,你会看到,close()
方法与标准大不相同。代码如下:
Mark the connection as closed, do cleanup, reset underlying connection state and params.
将连接标记为关闭,进行清理,重置底层连接状态和参数。
Hence, simply calling close()
will just clean and return the connection to the pool.
因此,简单地调用close()
只会清理并将连接返回到池中。