Reputation: 11
I need to connect a spring boot app with Cassandra DB in docker container and i need to create keyspace on spring app startup or even on Cassandra container start. How can i achieve this?
Upvotes: 1
Views: 340
Reputation: 1215
Spring Boot offers Schema Management for Cassandra, allowing you to create keyspaces through configuration. Here's an example implementation:
import java.util.List;
import lombok.NonNull;
import org.springframework.beans.factory.BeanClassLoaderAware;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.AbstractCassandraConfiguration;
import org.springframework.data.cassandra.core.cql.keyspace.CreateKeyspaceSpecification;
import org.springframework.data.cassandra.core.cql.keyspace.DataCenterReplication;
import org.springframework.data.cassandra.core.cql.keyspace.KeyspaceOption;
import org.springframework.data.cassandra.core.cql.keyspace.SpecificationBuilder;
@Configuration
public class CreateKeyspaceConfiguration extends AbstractCassandraConfiguration implements BeanClassLoaderAware {
@Value("${spring.cassandra.keyspace-name}")
private String keySpaceName;
@Override
@NonNull
protected String getKeyspaceName() {
return keySpaceName;
}
@Override
@NonNull
protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
CreateKeyspaceSpecification specification =
SpecificationBuilder.createKeyspace(keySpaceName)
.ifNotExists()
.with(KeyspaceOption.DURABLE_WRITES, true)
.withNetworkReplication(DataCenterReplication.of("datacenter1", 1));
return List.of(specification);
}
}
Here’s the corresponding application.properties
file:
spring.cassandra.keyspace-name=messaging
spring.cassandra.contact-points=127.0.0.1
spring.cassandra.port=9042
spring.cassandra.local-datacenter=datacenter1
spring.cassandra.schema-action=create_if_not_exists
Upvotes: 0
Reputation: 327
In your spring-boot java config you can have a bean which does this.
@Configuration
@PropertySource("classpath:cassandra.properties")
public class DaoConfig {
@Bean
public CassandraSessionManager getCassandraSessionManager() {
return new CassandraSessionManager();
}
}
If you are using datastax's cassandra java-driver, you can create your keyspace like below.
String query = "CREATE KEYSPACE mykeyspace WITH replication =
{'class':'SimpleStrategy','replication_factor':1};";
Cluster cluster = Cluster.builder().addContactPoint("127.0.0.1").build();
Session session = cluster.connect();
session.execute(query);
More common usecase is to connect to an existing keyspace, you can do that like https://github.com/joychakravarty/JNotes/blob/jnotes_withSpring/src/main/java/com/jc/jnotes/dao/remote/cassandra/CassandraSessionManager.java
Upvotes: 1