使用 Cassandra driver 时在 Java 项目中,管理连接的最佳实践是什么?具体来说,是允许多个线程共享单个 Cluster
实例更好,还是为每个需要与 Cassandra 通信的线程分配单独的 Cluster
实例更好。
我关注了example code并正在设置我的 Cluster
实例,例如:
Cluster.builder().addContactPoint(HOST).withPort(PORT)
.withCredentials(USER, PASS).build();
所以我要问的是,首选方法是执行类似的操作(单个共享集群
实例):
private static Cluster _cluster = null;
public static Cluster connect() {
if (_cluster != null && ! _cluster.isClosed()) {
//return the cached instance
return _cluster;
}
//create a new instance
_cluster = Cluster.builder().addContactPoint(HOST).withPort(PORT)
.withCredentials(USER, PASS).build();
return _cluster;
}
...或者返回多个 Cluster
实例是最佳实践吗?就像这样:
public static Cluster connect() {
//every caller gets their own Cluster instance
return Cluster.builder().addContactPoint(HOST).withPort(PORT)
.withCredentials(USER, PASS).build();
}
我想这个问题的核心要点是:
- 构建新的
集群
实例是一项昂贵的操作吗? Cluster
对象会在内部管理/池化与后备数据存储的连接,还是它的功能更像是单个连接的抽象?Cluster
对象是线程安全的吗?
最佳答案
Is building a new Cluster instance an expensive operation?
调用build构建Cluster实例不涉及网络IO,因此是一个成本不高的操作。
Will the Cluster object internally manage/pool connections to the backing datastore, or does it function more like an abstraction of a single connection?
昂贵的是调用cluster.init()
,它会创建一个到您的接触点之一的单个连接(控制连接)。 cluster.connect()
甚至更昂贵,因为它会初始化 Cluster(如果还没有)并创建 Session
它管理每个已发现主机的连接池(池大小基于您的 PoolingOptions )。所以,是的,Cluster
有一个“控制连接”来管理主机的状态,并且通过 Cluster.connect()
创建的每个 Session
将具有每个主机的连接池。
Is the Cluster object thread-safe?
简单地说,是的:)
4 simple rules when using the DataStax drivers for Cassandra提供有关此主题的进一步指导。
关于java - Cassandra 连接 - 共享 'Cluster' 实例或多个?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34734252/