Connecting to two cassandra databases from springboot application and read/write based on request header

Viewed 308

I am using springboot 2.5.7,cassandra-driver-core(3.3.0),spring-boot-starter-data-cassandra, java-driver-core to connect to a cassandra keyspace. In a changed requirement, I need to connect to two cassandra contact points with same schema and read from/write to one of them based on the parameter in the API header request. What is the best way to achieve this?

1 Answers

You would need to use two configuration classes to connect with two databases, and you would need to create two DataSource objects

for example:

Here you go.

you would need to, add multiple properties in your application.properties file:

#first db
spring.datasource.url = [url]
spring.datasource.username = [username]
spring.datasource.password = [password]
spring.datasource.driverClassName = [cassandra-driver-class-name]

#second db ...
spring.secondDatasource.url = [url]
spring.secondDatasource.username = [username]
spring.secondDatasource.password = [password]
spring.secondDatasource.driverClassName = [cassandra-driver-class-name]

Add in any class annotated with @Configuration the following methods:

@Bean
@Primary
@ConfigurationProperties(prefix="spring.datasource")
public DataSource primaryDataSource() {
    return DataSourceBuilder.create().build();
}

@Bean
@ConfigurationProperties(prefix="spring.secondDatasource")
public DataSource secondaryDataSource() {
    return DataSourceBuilder.create().build();
}
Related