Search code examples
springspring-bootcassandradatastaxspring-data-cassandra

How to add Cassandra MaxRequestsPerConnection using properties file in Spring boot


I have a Spring boot project, in which I use Cassandra as a database.

Currently, I am getting Cassandra instance by auto-wiring CassandraOperations.

My question is:

How can we set MaxRequestsPerConnection using a property file?

# spring.data.cassandra.keyspace-name=event
# spring.data.cassandra.contact-points=localhost
# spring.data.cassandra.port=9042

Currently, I have these properties on my property file, but I didn't found any property for setting MaxRequestsPerConnection


Solution

  • Spring Boot does not offer a configuration of all properties. You can define a ClusterBuilderCustomizer bean to customize Cluster instances.

    Try the following code to declare a customizer bean which gets properties injected that can be provided via a properties file (more generally speaking, any property source available to Spring Boot):

    @Configuration
    public class MyConfiguration {
    
        @Bean
        ClusterBuilderCustomizer clusterBuilderCustomizer(
                @Value("${spring.data.cassandra.pool.max-requests-local:10}") int local,
                @Value("${spring.data.cassandra.pool.max-requests-remote:5}") int remote) {
    
            PoolingOptions options = new PoolingOptions();
    
            options.setMaxRequestsPerConnection(HostDistance.LOCAL, local);
            options.setMaxRequestsPerConnection(HostDistance.REMOTE, remote);
    
            return builder -> builder.withPoolingOptions(options);
        }
    }
    

    An alternative to @Value is using a configuration class (annotated with @ConfigurationProperties which gives you IDE support (such as property-name auto-completion).