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

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

问题描述

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

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?

我是否应该在构造函数/初始化方法中创建我所有的 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 一次并在应用程序运行时缓存它.只要 Cassandra 集群启动,它就应该可用.

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.

使用来自多个线程的语句是可以的(只要你不通过 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.

这里是源代码,如果你好奇的话(搜索bind()).

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

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

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