在 Datastax 驱动程序中使用 LOCAL_QUORUM 一致性级别

Usage of the LOCAL_QUORUM consistency level in Datastax driver

出于某些原因,我需要查询我的 cassandra 集群中的特定数据中心。根据the documentation,我可以使用LOCAL_QUORUM一致性级别:

Returns the record after a quorum of replicas in the current datacenter as the coordinator has reported. Avoids latency of inter-datacenter communication.

我是否正确理解,为了为当前查询指定一个特定的数据中心,我必须在属于这个特定 DC 的给定端点上构建一个集群?

比如说,我有两个具有以下节点的 DC:

DC1: 172.0.1.1, 172.0.1.2
DC1: 172.0.2.1, 172.0.2.2

因此,为了使用 DC1,我构建了一个集群:

Cluster cluster = Cluster.builder().addContactPoint("172.0.1.1").build();
Session session = cluster.connect();
Statement statement = session.prepare("select * from ...").bind().setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM);
ResultSet resultSet = session.execute(session);

这样做正确吗?

根据 Cluster class documentation:

A cluster object maintains a permanent connection to one of the cluster nodes which it uses solely to maintain information on the state and current topology of the cluster

此外,因为 a default load balancing policyDCAwareRoundRobinPolicy,所以这种方法应该可以正常工作。

DCAwwareRoundRobinPolicy 本身将选择它使用 "least network distance" 算法找到的数据中心。为确保它连接到您想要的位置,您应该将 DC 指定为参数。

以下是我告诉我们的开发团队的方法:

Builder builder = Cluster.builder()
  .addContactPoints(nodes)
  .withQueryOptions(new QueryOptions()
    .setConsistencyLevel(ConsistencyLevel.LOCAL_ONE))
  .withLoadBalancingPolicy(new TokenAwarePolicy(
    new DCAwareRoundRobinPolicy.Builder()
      .withLocalDc("DC1").build()))
  .withPoolingOptions(options);

注意:这可能适用于您的情况,也可能不适用于您的情况,但我是否建议将 TokenAwarePolicyDCAwareRoundRobin 嵌套在 内部 中使用(指定本地 DC)。这样,任何指定分区键的操作都会自动路由到正确的节点,而无需协调器节点所需的额外跃点。