管理Java servlet的数据库连接的最佳方法 [英] Best way to manage database connection for a Java servlet

查看:163
本文介绍了管理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).

推荐答案

p>我实际上不同意使用Commons DBCP。

I actually disagree with using Commons DBCP. You should really defer to the container to manage connection pooling for you.

因为你使用的是Java Servlets,这意味着在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.

这篇关于管理Java servlet的数据库连接的最佳方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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