在使用Datastax Cassandra驱动程序时重新使用PreparedStatement? [英] Re-using PreparedStatement when using Datastax Cassandra Driver?

查看:1671
本文介绍了在使用Datastax Cassandra驱动程序时重新使用PreparedStatement?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我目前正在使用Cassandra 2的Datastax Cassandra驱动程序来执行cql3。这工作正常。我开始使用 PreparedStatement的

I'm currently using the Datastax Cassandra driver for Cassandra 2 to execute cql3. This works correctly. I started using PreparedStatement's:

Session session = sessionProvider.getSession();
try {
    PreparedStatement ps = session.prepare(cql);
    ResultSet rs = session.execute(ps.bind(objects));
    if (irsr != null) {
       irsr.read(rs);
    }
}

有时候我在日志中收到驱动程序的警告:

Sometimes I get a warning from the driver in my log:

Re-preparing already prepared query . Please note that preparing the same query more than once is generally an anti-pattern and will likely affect performance. Consider preparing the statement only once.

这个警告是有意义的,但我不知道我应该如何重用 PreparedStatement

This warning makes sense, but i'm not sure how i should reuse the PreparedStatement?

我应该在构造函数/ init中创建所有 PreparedStatement 方法,而不是简单地使用它们?

Should I just create all my PreparedStatement in a constructor/init method and than simply use them?

但是,当多个线程在同一个线程中使用相同的 PreparedStatement 时间(特别是调用 PreparedStatement.bind()来绑定对象)

But does this go well when multiple threads use the same PreparedStatement at the same time (especially calling PreparedStatement.bind() to bind objects)

推荐答案

您可以只初始化PreparedStatement一次,并在应用程序运行时缓存它。

You may just initialize the PreparedStatement once and cache it while the app is running. It should be available for use as long as the Cassandra cluster is up.

使用多个线程的语句很好(只要你不修改它通过t setXXX()方法)。当调用bind()时,下面的代码只读取PreparedStatement,然后创建一个BoundStatement()的新实例,然后调用者线程可以自由变异。

Using the statement from multiple threads is fine (as long as you don't modify it throught setXXX() methods). When you call bind(), the code underneath only reads the PreparedStatement and then creates a new instance of BoundStatement() which the caller thread is then free to mutate.

a href =https://github.com/datastax/java-driver/blob/5d0f8aff0813399aa92dee942b6c62a093f7ed12/driver-core/src/main/java/com/datastax/driver/core/DefaultPreparedStatement.java>这是源代码,如果您好奇(搜索 bind())。

Here is the source code, if you're curious (search for bind()).

这篇关于在使用Datastax Cassandra驱动程序时重新使用PreparedStatement?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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