0

我的应用程序使用凭据与 Cassandra 集群连接。我正在创建一个 TestCassandra 的实例,如下所示:

val testCassandra = cqlStatementsOption.map(cqlStatements =>{
    new TestCassandra(factory,cqlStatements)})
    .getOrElse(new TestCassandra())

我想上面的语句会创建一个集群。如何为创建的集群指定用户名和密码?我的一个测试用例是,如果 cassandra 数据库的用户名/密码不正确,则应用程序不应启动。

4

1 回答 1

0
class SecureCassandra {

    private final TestCassandra testCassandra = new TestCassandra(createCassandraFactory(), createConnectionFactory(),
            CqlScript.classpath("init.cql"));

    private ConnectionFactory createConnectionFactory() {
        ClusterFactory clusterFactory = new ClusterFactory();
        clusterFactory.setUsername("cassandra");
        clusterFactory.setPassword("cassandra");
        return new ClusterConnectionFactory(clusterFactory);
    }

    private CassandraFactory createCassandraFactory() {
        LocalCassandraFactory cassandraFactory = new LocalCassandraFactory();
        cassandraFactory.setConfigurationFile(getClass().getResource("/cassandra-secure.yaml"));
        cassandraFactory.getJvmOptions().add("-Dcassandra.superuser_setup_delay_ms=0");
        return cassandraFactory;
    }

    @Test
    void testSecureCassandra() {
        this.testCassandra.start();

        try {
            Settings settings = this.testCassandra.getSettings();
            ClusterFactory clusterFactory = new ClusterFactory();
            clusterFactory.setUsername("test_user");
            clusterFactory.setPassword("test_pass");
            try (Cluster cluster = clusterFactory.create(settings)) {
                try (Session session = cluster.connect("test")) {
                    //
                }
            }

        }
        finally {
            this.testCassandra.stop();
        }
    }

}

初始化.cql:

CREATE KEYSPACE test  WITH REPLICATION = { 'class' : 'SimpleStrategy', 'replication_factor' : 1 };
CREATE ROLE test_user with SUPERUSER = true AND LOGIN = true and PASSWORD = 'test_pass';

cassandra-secure.yaml:

cluster_name: "Test Cluster"
num_tokens: 256
commitlog_sync: periodic
commitlog_sync_period_in_ms: 5000
seed_provider:
  - class_name: org.apache.cassandra.locator.SimpleSeedProvider
    parameters:
      - seeds: "127.0.0.1"
listen_address: localhost
rpc_address: localhost
start_native_transport: true
endpoint_snitch: SimpleSnitch
partitioner: org.apache.cassandra.dht.Murmur3Partitioner
authenticator: PasswordAuthenticator
role_manager: CassandraRoleManager
authorizer: CassandraAuthorizer
于 2020-07-08T10:12:28.253 回答