Search code examples
javacassandradatastax-java-driver

What is the right approach to migrating QueryOptions to the new Cassandra Java driver v4.14?


I am migrating from Datastax Cassandra Driver 1.9 to 4.14.x

I would be interested how to migrate this code:

Builder builder =
        Cluster.builder()
            .withQueryOptions(new QueryOptions().setConsistencyLevel(ConsistencyLevel.LOCAL_QUORUM));

Is that the right approach and the equivalent to the code above?

DriverConfigLoader driverConfigLoader = DriverConfigLoader.programmaticBuilder()
        .withString(DefaultDriverOption.REQUEST_CONSISTENCY, "LOCAL_QUORUM")
        .build();
    final CqlSessionBuilder cqlSessionBuilder =
        CqlSession.builder()
            .withConfigLoader(driverConfigLoader);

Thanks in advance!


Solution

  • With the drivers 4.x keys configuration keys be defined in application.conf. As long as the file is in the classpath it will load properties and it is the best way to setup your application without having to change your code. documentation

    Knowing this, if you still want to do configuration programmatically you indeed have the correct approach:

     DriverConfigLoader loader = DriverConfigLoader.programmaticBuilder()
            .withStringList(DefaultDriverOption.CONTACT_POINTS, Arrays.asList("127.0.0.1:9042"))
            .withString(DefaultDriverOption.REQUEST_CONSISTENCY, "LOCAL_QUORUM")
            .withString(DefaultDriverOption.LOAD_BALANCING_LOCAL_DATACENTER, "datacenter1")
            .withString(DefaultDriverOption.SESSION_KEYSPACE, KEYSPACE_NAME)
            .withDuration(DefaultDriverOption.REQUEST_TIMEOUT, Duration.ofSeconds(5))
            
            // If you want to override with an execution profile
            .startProfile("slow")
            .withDuration(DefaultDriverOption.REQUEST_TIMEOUT, Duration.ofSeconds(30))
            .endProfile()
            .build();
        // Use it to create the session
        try (CqlSession cqlSession = CqlSession.builder().withConfigLoader(loader).build()) {
            
            // Use session
            LOGGER.info("[OK] Connected to Keyspace {}", cqlSession.getKeyspace().get());
        }
      
    

    A lot of 4.x code can be found here and used as reference.