在 Tomcat 中缓存准备好的语句的好策略是什么?
我正在寻找一种在 servlet 环境(特别是 Tomcat 5.5)中缓存准备好的语句的方法。 这是为了减少创建准备语句的次数,即调用connection.prepareStatement(sql)
的次数。
我最初的想法是在会话中存储 PreparedStatement
对象,其中键(属性名称)是查询本身。 这也可以懒惰地完成。
然而,有人提醒我这样一个事实:根据 JDBC 驱动程序的实现,同一个准备好的语句可能会同时被 2 个线程(或请求)访问,从而导致例如设置错误的参数。 因此,对这些statement对象的访问需要同步。
实现这一目标的好策略是什么?
tomcat 中是否有内置方法来执行此操作? 我看到这个答案其中提到了poolPreparedStatements
DBCP 参数,但从文档中并不完全清楚它是否与我正在寻找的含义相同。
I am looking for a way to cache prepared statements in a servlet environment (specifically, Tomcat 5.5). This is meant to reduce the number of times that prepared statements are created, i.e. the number of times that connection.prepareStatement(sql)
is called.
My initial idea was to store PreparedStatement
objects in the session, where the key (the attribute name) is the query itself. This can also be done lazily.
However, someone alerted me to the fact that, depending on the JDBC driver implementation, the same prepared statement may be accessed by 2 threads (or requests) simultaneously, resulting, for example, in the wrong parameters being set. Therefore, the access to these statement objects needs to be synchronized.
What would be a good strategy to achieve this?
Is there a method built in to tomcat for doing this? I have see this answer where it mentions the poolPreparedStatements
DBCP parameter, but it's not entirely clear from the documentation if it carries the same meaning as what I'm looking for.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
PreparedStatement 缓存通常由您正在使用的连接池提供。
请注意,在连接池的工作方式中,一个线程获取一个连接,将其用于某些 sql 查询并将其返回到池中。 只有这样该连接才可用于另一个线程。 除非连接池中存在错误,否则连接不会在线程之间并发共享。
顺便说一句 - 我的建议是使用 c3p0 而不是 DBCP。 我在 DBCP 方面遇到了很多问题,一旦我迁移到 c3p0,这些问题就得到了解决。
PreparedStatement caching is usually provided by the connection pool you are using.
Notice that in the way connection pool works, one thread acquires a connection, use it for some sql queries and return it to the pool. Only then the connection is available to another thread. Unless there is a bug in in the connection pool, connections are not shared among threads concurrently.
BTW - my recommendation is to use c3p0 and not DBCP. I had a lot of issues with DBCP that were solved once I moved to c3p0.
我不确定其他数据库的情况,但如果您使用Oracle,则 JDBC 客户端将缓存PreparedStatement。 您可能想看看您的数据库是否这样做。
I'm not sure about other DBs, but if you're using Oracle, the JDBC client will cache the PreparedStatement. You might want to see if your DB does that.