JSP站点的连接池策略? [英] Connection Pooling Strategy For A JSP Site?

查看:79
本文介绍了JSP站点的连接池策略?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在一个JSP站点上做一些工作,该站点的代码编写得很糟糕.对于每个数据库调用,原始程序员都会打开和关闭数据库连接.我添加了一些新的数据库操作,我想做的更好一些(稍后可以重建更多站点时,将出现诸如休眠之类的东西).我正在考虑在会话开始时(登录后)创建一个数据库连接,将其存储在会话对象中,然后在会话关闭时在会话处理函数的会话侦听器末尾将其关闭.这是一个合理的策略吗?有想法吗?

I'm doing some work on a JSP site that was coded very badly. For every single database call the original programmer opens and closes a database connection. I'm adding in some new database operations and I would like to do things a little bit better( something like hibernate will come later when more of the site can be rebuilt ). I was thinking of creating a single database connection when a session starts ( after logging in ), storing it in the session object and then closing it in session listener end of session handling function when the session closes. Is this a sound strategy? Thoughts?

推荐答案

我正在考虑在会话启动时(登录后)创建一个数据库连接,将其存储在会话对象中,然后在会话关闭时在会话处理功能的会话侦听器末尾将其关闭.这是一个合理的策略吗?有想法吗?

不.创建一个容器管理的连接池数据源,并在Webapp启动时由JNDI获取.

No. Create a container managed connection pooled data source and get it by JNDI on webapp's startup.

如何创建数据源取决于所涉及的容器.例如,对于Tomcat 6.0,您可以在此处阅读: http://localhost:4848 上进行.

How to create the data source depends on the container in question. In case of for example Tomcat 6.0, you can read it up here: Tomcat JNDI Resources HOW-TO - JDBC Data Sources. In case of for example Glassfish 3, you can do it in the webbased admin console on http://localhost:4848.

这是您最终可以从JNDI获得它的方法:

Here's how you can finally get it from JNDI:

DataSource dataSource = (DataSource) new InitialContext().lookup(jndiName);
// ...

您可以在其上呼叫getConnection().仅在webapp启动期间获取一次数据源就足够了,例如,在数据库连接管理器的静态初始化程序块中,或者在ServletContextListener中.

You can call getConnection() on it. It's sufficient to get the data source only once during webapp's startup, for example in a static initializer block of your database connection manager or perhaps in a ServletContextListener.

应始终在尽可能短的范围内获取并关闭连接.在执行查询的try块中获取它,并在与之完全相同的try块的finally中将其关闭.断开连接的时间不要超过必要的时间.连接池将确保它们保持打开状态,因此该性能已经得到了极大的改善.

The connection should always be acquired and closed in the shortest possible scope. Get it inside the try block where you're executing the query and close it in the finally of the very same try block. Do not keep the connection open longer than necessary. The connection pool will take care about keeping them open, so the performance is already greatly improved that way.

这篇关于JSP站点的连接池策略?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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