Cassandra 会话线程安全吗? (使用 cpp 驱动程序)

Is a cassandra session thread safe? (using cpp driver)

我正在开发一个多线程应用程序并使用 Cassandra 作为后端。

之前,我为每个子线程创建了一个单独的会话,并在线程执行结束前关闭会话。但后来我认为这可能是一项昂贵的工作,所以我现在将其设计为,我在服务器启动时打开了一个会话,任意数量的客户端都可以使用该会话进行查询。

问题:我只想知道这是否正确,或者有更好的方法吗?我知道连接池是一个选项,但在这种情况下真的需要吗?

在 Java 驱动程序中肯定是线程安全的,所以我假设 C++ 驱动程序是相同的。

我们鼓励您只创建一个会话并让您的所有线程都使用它,以便驱动程序可以有效地维护一个到集群的连接池并异步处理来自您的客户端线程的命令。

如果您在一台客户端计算机上创建多个会话或不断打开和关闭会话,您将迫使驱动程序不断建立和删除与集群的连接,这会浪费资源。

在使用 Cassandra 的 DataStax 驱动程序时引用 this Datastax blog post 关于 4 条简单规则:

  1. Use one Cluster instance per (physical) cluster (per application lifetime)
  2. Use at most one Session per keyspace, or use a single Session and explicitely specify the keyspace in your queries
  3. If you execute a statement more than once, consider using a PreparedStatement
  4. You can reduce the number of network roundtrips and also have atomic operations by using Batches

C/C++ 驱动程序在会话和未来级别绝对是线程安全的。

The CassSession object is used for query execution. Internally, a session object also manages a pool of client connections to Cassandra and uses a load balancing policy to distribute requests across those connections. An application should create a single session object per keyspace as a session object is designed to be created once, reused, and shared by multiple threads within the application.

他们实际上有一个部分叫做 线程安全:

A CassSession is designed to be used concurrently from multiple threads. CassFuture is also thread safe. Other than these exclusions, in general, functions that might modify an object’s state are NOT thread safe. Objects that are immutable (marked ‘const’) can be read safely by multiple threads.

他们还有关于释放对象的说明。那不是线程安全的。因此,在释放对象之前,您必须确保所有线程都已完成:

NOTE: The object/resource free-ing functions (e.g. cass_cluster_free, cass_session_free, … cass_*_free) cannot be called concurrently on the same instance of an object.

来源:

http://datastax.github.io/cpp-driver/topics/