jsevellec / cassandra-unit

Utility tool to load Data into Cassandra to help you writing good isolated JUnit Test into your application
GNU Lesser General Public License v3.0
424 stars 1 forks source link

Instantiate Connection Lazy when needed #269

Closed SvenssonWeb closed 6 years ago

SvenssonWeb commented 6 years ago

When the Embedded Cassandra Instance is created a default cluster/session connection is initiated as well.

https://github.com/jsevellec/cassandra-unit/blob/fec9cb47843b3f9935a0320f24288ed9ab73ff5f/cassandra-unit/src/main/java/org/cassandraunit/utils/EmbeddedCassandraServerHelper.java#L159-L172

When using other configuration than standard, this internal connection will fail and throw exceptions. I'd like to move this execution to the getCluster() and getSession() methods, and instantiate it when needed. https://github.com/jsevellec/cassandra-unit/blob/fec9cb47843b3f9935a0320f24288ed9ab73ff5f/cassandra-unit/src/main/java/org/cassandraunit/utils/EmbeddedCassandraServerHelper.java#L219-L225

I'm thinking about something like this:

    public static com.datastax.driver.core.Cluster getCluster() {
        initCluster();
        return cluster;
    }

    public static Session getSession() {
        initSession();
        return session;
    }

    private static synchronized void initCluster() {
        if (cluster == null) {
            QueryOptions queryOptions = new QueryOptions();
            queryOptions.setRefreshSchemaIntervalMillis(0);
            queryOptions.setRefreshNodeIntervalMillis(0);
            queryOptions.setRefreshNodeListIntervalMillis(0);
            cluster = com.datastax.driver.core.Cluster.builder()
                    .addContactPoints(EmbeddedCassandraServerHelper.getHost())
                    .withPort(EmbeddedCassandraServerHelper.getNativeTransportPort())
                    .withQueryOptions(queryOptions)
                    .build();
        }
    }

    private static synchronized void initSession() {
        if (session == null) {
            initCluster();
            session = cluster.connect();
        }
    }