How to initialize Cassandra keyspace and tables wi

2019-06-22 19:24发布

I am using Cassandra as a datasource in my Spring boot application and would like to initialize the database before the application starts.

Up to now what I have done is, I have defined a class "CassandraConfiguration" extending "AbstractCassandraConfiguration" class as in the examples which you can see below and I have a repository extending "CassandraRepository". When I create the keyspace and the table myself, the application works fine.

However, I want to create the keyspace and tables automatically while application is starting. In order to do that, I supplied a schema.cql file under resources folder but I could not make that script work.

Does anyone have any idea what can I do to create the keyspace(s) and tables automatically?

Thanks.

Edit: I am using Cassandra 2.0.9, spring-boot 1.3.2.RELEASE and datastax cassandra driver 2.1.6 versions.

CassandraConfiguration.java

@Configuration
@PropertySource(value = { "classpath:cassandra.properties" })
@EnableCassandraRepositories(basePackages = { "bla.bla.bla.repository" })
public class CassandraConfiguration extends AbstractCassandraConfiguration {

    @Autowired
    private Environment environment;


    @Bean
    public CassandraClusterFactoryBean cluster() {
        CassandraClusterFactoryBean cluster = new CassandraClusterFactoryBean();
        cluster.setContactPoints( environment.getProperty( "cassandra.contactpoints" ) );
        cluster.setPort( Integer.parseInt( environment.getProperty( "cassandra.port" ) ) );
        return cluster;
    }


    @Bean
    public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
        return new BasicCassandraMappingContext();
    }


    @Bean
    public CassandraConverter converter() throws ClassNotFoundException {
        return new MappingCassandraConverter(cassandraMapping());
    }


    @Override
    protected String getKeyspaceName() {
        return environment.getProperty( "cassandra.keyspace" );
    }


    @Bean
    public CassandraSessionFactoryBean session() throws Exception {

        CassandraSessionFactoryBean session = new CassandraSessionFactoryBean();
        session.setCluster(cluster().getObject());
        session.setKeyspaceName(environment.getProperty("cassandra.keyspace"));
        session.setConverter(converter());
        session.setSchemaAction(SchemaAction.NONE);

        return session;
    }


    @Override
    public SchemaAction getSchemaAction() {
        return SchemaAction.RECREATE_DROP_UNUSED;
    }
}

4条回答
贪生不怕死
2楼-- · 2019-06-22 19:48

Finally i got it working by adding setKeyspaceCreations(getKeyspaceCreations()) to the CassandraClusterFactoryBean Override and also make sure to enable @ComponentScan.

import com.datastax.driver.core.PlainTextAuthProvider;
import com.datastax.driver.core.policies.ConstantReconnectionPolicy;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.cassandra.config.*;
import org.springframework.data.cassandra.core.cql.keyspace.CreateKeyspaceSpecification;
import org.springframework.data.cassandra.core.cql.keyspace.DropKeyspaceSpecification;
import org.springframework.data.cassandra.core.cql.keyspace.KeyspaceOption;
import org.springframework.data.cassandra.repository.config.EnableReactiveCassandraRepositories;

import java.util.Arrays;
import java.util.List;



@Configuration
@EnableReactiveCassandraRepositories(basePackages = "com.company.domain.data")
public class CassandraConfig extends AbstractReactiveCassandraConfiguration{
@Value("${spring.data.cassandra.contactpoints}") private String contactPoints;
@Value("${spring.data.cassandra.port}") private int port;
@Value("${spring.data.cassandra.keyspace-name}") private String keyspace;

@Value("${spring.data.cassandra.username}") private String userName;
@Value("${spring.data.cassandra.password}") private String password;
@Value("${cassandra.basepackages}") private String basePackages;


@Override protected String getKeyspaceName() {
    return keyspace;
}
@Override protected String getContactPoints() {
    return contactPoints;
}
@Override protected int getPort() {
    return port;
}
@Override public SchemaAction getSchemaAction() {
    return SchemaAction.CREATE_IF_NOT_EXISTS;
}
@Override
public String[] getEntityBasePackages() {
    return new String[]{"com.company.domain.data"};
}

@Override
public CassandraClusterFactoryBean cluster() {
    PlainTextAuthProvider authProvider = new PlainTextAuthProvider(userName, password);

    CassandraClusterFactoryBean cluster=new CassandraClusterFactoryBean();

    cluster.setJmxReportingEnabled(false);
    cluster.setContactPoints(contactPoints);
    cluster.setPort(port);
    cluster.setAuthProvider(authProvider);
    cluster.setKeyspaceCreations(getKeyspaceCreations());
    cluster.setReconnectionPolicy(new ConstantReconnectionPolicy(1000));

    return cluster;
}


@Override
protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {

    CreateKeyspaceSpecification specification = CreateKeyspaceSpecification.createKeyspace(keyspace)
            .ifNotExists()
            .with(KeyspaceOption.DURABLE_WRITES, true);

    return Arrays.asList(specification);
}



@Override
protected List<DropKeyspaceSpecification> getKeyspaceDrops() {
    return Arrays.asList(DropKeyspaceSpecification.dropKeyspace(keyspace));
}



}
查看更多
做个烂人
3楼-- · 2019-06-22 19:51

Your return type BasicCassandraMappingContext() might be deprecated. Use

@Bean
public CassandraMappingContext mappingContext() throws ClassNotFoundException {
    CassandraMappingContext mappingContext= new CassandraMappingContext();
    mappingContext.setInitialEntitySet(getInitialEntitySet());
    return mappingContext;
}
@Override
public String[] getEntityBasePackages() {
    return new String[]{"base-package name of all your entity, annotated 
with @Table"};
}

@Override
protected Set<Class<?>> getInitialEntitySet() throws ClassNotFoundException {
    return CassandraEntityClassScanner.scan(getEntityBasePackages());
}

Instead of,

@Bean
public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
    return new BasicCassandraMappingContext();
}

also set:

session.setSchemaAction(SchemaAction.RECREATE_DROP_UNUSED);

and Exclude:

@Override
public SchemaAction getSchemaAction() {
    return SchemaAction.RECREATE_DROP_UNUSED;
}

get reference here.

查看更多
闹够了就滚
4楼-- · 2019-06-22 19:54

I'm working with spring-boot 1.5.10.RELEASE and cassandra 3.0.16 but you can try downscaling the versions. To create the keyspace you can import the keyspacename from you application.yml or application.properties. Using the @Table annotation your tables should be generated automatically provided you have set the entity base package.

@Value("${cassandra.keyspace}")
private String keySpace;

@Override
public String[] getEntityBasePackages() {
    return new String[]{"com.example.your.entities"};
}

@Override
protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
    return Arrays.asList(
            CreateKeyspaceSpecification.createKeyspace()
                    .name(keySpace)
                    .ifNotExists()
    );
}
查看更多
我想做一个坏孩纸
5楼-- · 2019-06-22 19:57

If you are still having problems with this, in Spring Boot 2 and SD Cassandra 2.0.3 you can do this straightforward Java configuration and setup everything out of the box.

@Configuration
@EnableCassandraRepositories(basePackages = "com.example.repository")
public class DbConfigAutoStart extends AbstractCassandraConfiguration {

    /*
     * Provide a contact point to the configuration.
     */
    @Override
    public String getContactPoints() {
        return "exampleContactPointsUrl";
    }

    /*
     * Provide a keyspace name to the configuration.
     */
    @Override
    public String getKeyspaceName() {
        return "exampleKeyspace";
    }

    /*
     * Automatically creates a Keyspace if it doesn't exist
     */
    @Override
    protected List<CreateKeyspaceSpecification> getKeyspaceCreations() {
        CreateKeyspaceSpecification specification = CreateKeyspaceSpecification
                .createKeyspace("exampleKeyspace").ifNotExists()
                .with(KeyspaceOption.DURABLE_WRITES, true).withSimpleReplication();
        return Arrays.asList(specification);
    }


    /*
     * Automatically configure a table if doesn't exist
     */
    @Override
    public SchemaAction getSchemaAction() {
        return SchemaAction.CREATE_IF_NOT_EXISTS;
    }


    /*
     * Get the entity package (where the entity class has the @Table annotation)
     */
    @Override
    public String[] getEntityBasePackages() {
        return new String[] { "com.example.entity" };
    }

And you are good to go

查看更多
登录 后发表回答