spring-projects / spring-data-cassandra

Provides support to increase developer productivity in Java when using Apache Cassandra. Uses familiar Spring concepts such as a template classes for core API usage and lightweight repository style data access.
https://spring.io/projects/spring-data-cassandra/
Apache License 2.0
374 stars 307 forks source link

How to configure Datastax Astra using `AbstractCassandraConfiguration` #1447

Closed miladamery closed 8 months ago

miladamery commented 9 months ago

Hi, I have an app that is using spring(not spring boot) that requires to connect to Datastax Astra DB. There is a solution in case spring boot is available. but that is not an option for me and I couldn't find out how to do this via AbstractReactiveCassandraConfiguration. Thanks in advance.

mp911de commented 8 months ago

AbstractReactiveCassandraConfiguration creates a CQL session when configuring beans.

If you want to build a configuration that is robust against Cassandra absence, then you cannot:

You also need to provide a SessionFactory implementation to defer session creation to a later time.

miladamery commented 8 months ago

Thanks but I want to ask if this works. I looked at how spring boot configures CqlSession for Astra Db. There is CqlSessionCustomizer that does the job. Spring boot setups CqlSession via a CqlSessionBuilder setting contact points, setting keyspace etc but at the end calling the customizer. According to this stack question and examples in datastax repos something like below does the job:

@Bean
public CqlSessionBuilderCustomizer sessionBuilderCustomizer(DataStaxAstraProperties astraProperties) {
    Path bundle = astraProperties.getSecureConnectBundle().toPath();
    return builder -> builder.withCloudSecureConnectBundle(bundle);
}

Almost same identical code exists in normal spring data cassandra. in AbstractSessionConfiguration there is method SessionBuilderConfigurer. What happens here is almost the same thing that happens in spring boot. So I wonder if the following does the job of connecting to astra Db with connect bundle file:

public class ReactiveCassandraConfig extends AbstractReactiveCassandraConfiguration {

    private String keySpace;

    private String connectBundlePath;
    @Override
    protected String getKeyspaceName() {
        return keySpace;
    }

    @Override
    protected SessionBuilderConfigurer getSessionBuilderConfigurer() {
        return sessionBuilder -> sessionBuilder
                .withCloudSecureConnectBundle(Path.of(connectBundlePath));
    }
}
mp911de commented 8 months ago

Sorry, I misunderstood your question and now that you've posted some code, it made it clear what you're asking for. So SessionBuilderConfigurer available on AbstractSessionConfiguration and its subclasses is the way to go.

It makes sense to document SessionBuilderConfigurer in our reference documentation to make it easier to find what you were asking for.