为 Java servlet 管理数据库连接的最佳方法
在 Java servlet 中管理数据库连接的最佳方法是什么?
What is the best way to manage a database connection in a Java servlet?
目前,我只是在 init()
函数中打开一个连接,然后在 destroy()
中关闭它.
Currently, I simply open a connection in the init()
function, and then close it in destroy()
.
但是,我担心永久"保持数据库连接可能是一件坏事.
However, I am concerned that "permanently" holding onto a database connection could be a bad thing.
这是处理这个问题的正确方法吗?如果没有,有什么更好的选择?
Is this the correct way to handle this? If not, what are some better options?
提供更多说明:我尝试为每个请求简单地打开/关闭一个新连接,但通过测试我发现由于创建太多连接而导致性能问题.
edit: to give a bit more clarification: I have tried simply opening/closing a new connection for each request, but with testing I've seen performance issues due to creating too many connections.
通过多个请求共享连接有什么价值吗?此应用程序的请求几乎都是只读"的,而且来得相当快(尽管请求的数据相当少).
Is there any value in sharing a connection over multiple requests? The requests for this application are almost all "read-only" and come fairly rapidly (although the data requested is fairly small).
推荐答案
我实际上不同意使用 Commons DBCP.你真的应该让容器为你管理连接池.
I actually disagree with using Commons DBCP. You should really defer to the container to manage connection pooling for you.
由于您使用的是 Java Servlet,这意味着在 Servlet 容器中运行,并且我熟悉的所有主要 Servlet 容器都提供连接池管理(Java EE 规范甚至可能需要它).如果您的容器碰巧使用 DBCP(就像 Tomcat 一样),那很好,否则,只需使用您的容器提供的任何内容.
Since you're using Java Servlets, that implies running in a Servlet container, and all major Servlet containers that I'm familiar with provide connection pool management (the Java EE spec may even require it). If your container happens to use DBCP (as Tomcat does), great, otherwise, just use whatever your container provides.
相关文章