Scala“无法在对象CassandraConnector中访问类DCAwareRoundRobinPolicy中的构造函数DCAwareRoundRobinPolicy”

问题描述

我是Scala的新手,在我遇到一些代码问题时确实需要帮助。我设置了以下代码来创建cassandra连接:

package some.package

import java.net.InetAddress
import java.util

import com.datastax.driver.core._
import com.datastax.driver.core.policies.{DCAwareRoundRobinPolicy,TokenAwarePolicy}

import scala.collection.JavaConversions._

object CassandraConnector {

  def getCluster(contactPointIpString: String,preferred_dc: String): Cluster = {

    val contactPointIpStrings = contactPointIpString.split(",").toList

    val contactPointIpList = contactPointIpStrings.flatMap { ipAddress: String => InetAddress.getAllByName(ipAddress) }
    println(s"Building Cluster w/ Contact Points: $contactPointIpList")

    Cluster.builder()
      .addContactPoints(contactPointIpList)
      .withClusterName("multi_dc_user_data")
      .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy(preferred_dc)))
      .withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.LOCAL_ONE))
      .build()
  }

}

在IntelliJ中构建项目时,发生以下错误

constructor DCAwareRoundRobinPolicy in class DCAwareRoundRobinPolicy cannot be accessed in object CassandraConnector
      .withLoadBalancingPolicy(new TokenAwarePolicy(new DCAwareRoundRobinPolicy(preferred_dc)))

发现了与我的问题here类似的内容,并尝试将我的代码更改为以下内容

val dcAwareRoundRobinPolicyBuilder = new DCAwareRoundRobinPolicy.Builder
val dcAwareRoundRobinPolicy = dcAwareRoundRobinPolicyBuilder.withLocalDc(preferred_dc)

Cluster.builder()
  .addContactPoints(contactPointIpList)
  .withClusterName("multi_dc_user_data")
  .withLoadBalancingPolicy(new TokenAwarePolicy(dcAwareRoundRobinPolicy.build()))
  .withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.LOCAL_ONE))
  .build()

解决了问题,现在构建成功完成,但是我不确定我所做的工作是否一定正确,因此,我非常感谢在这方面的任何帮助。

解决方法

DCAwareRoundRobinPolicy使用构建器模式将实例创建的公共API与实例的构造函数的特定实现分离。这是通过不公开公共构造函数,而只允许DCAwareRoundRobinPolicy.Builder构造DCAwareRoundRobinPolicy的实例来实现的。

您正在按预期使用它(假设您要传递与期望值匹配的选项)。