[英]How to initialize Cassandra keyspace and tables with Spring boot
我在 Spring boot 应用程序中使用 Cassandra 作为数据源,并希望在应用程序启动之前初始化数据库。
到目前为止,我所做的是,我定义了一个扩展“AbstractCassandraConfiguration”类的“CassandraConfiguration”类,如下例所示,我有一个扩展“CassandraRepository”的存储库。 当我自己创建键空间和表时,应用程序工作正常。
但是,我想在应用程序启动时自动创建键空间和表。 为了做到这一点,我在资源文件夹下提供了一个 schema.cql 文件,但我无法使该脚本工作。
有谁知道我可以做什么来自动创建键空间和表?
谢谢。
编辑:我使用的是 Cassandra 2.0.9、spring-boot 1.3.2.RELEASE 和 datastax cassandra 驱动程序 2.1.6 版本。
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;
}
}
如果您仍然遇到此问题,在Spring Boot 2和SD Cassandra 2.0.3中,您可以直接进行Java配置并开箱即用。
@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" };
}
你很高兴
您的返回类型BasicCassandraMappingContext()可能已被弃用。 使用
@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());
}
代替,
@Bean
public CassandraMappingContext cassandraMapping() throws ClassNotFoundException {
return new BasicCassandraMappingContext();
}
还设置:
session.setSchemaAction(SchemaAction.RECREATE_DROP_UNUSED);
并排除:
@Override
public SchemaAction getSchemaAction() {
return SchemaAction.RECREATE_DROP_UNUSED;
}
在这里得到参考。
我正在使用spring-boot 1.5.10.RELEASE
和cassandra 3.0.16
但你可以尝试缩减版本。 要创建键空间,可以从application.yml
或application.properties
导入keyspacename。 如果已设置实体基础包,则应使用@Table
注释自动生成表。
@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()
);
}
最后,我通过将setKeyspaceCreations(getKeyspaceCreations())添加到CassandraClusterFactoryBean Override并确保启用@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));
}
}
之前的答案基于spring-data-cassandra
AbstractCassandraConfiguration
。 如果您使用spring-boot
那么它可以为您自动配置 Cassandra 并且无需扩展AbstractCassandraConfiguration
。 但是,即使在这种情况下,您也需要做一些工作来自动创建键空间。 我已经决定将自动配置添加到我们公司的 spring-boot 启动器中,但您也可以将其定义为应用程序中的常规配置。
/**
* create the configured keyspace before the first cqlSession is instantiated. This is guaranteed by running this
* autoconfiguration before the spring-boot one.
*/
@ConditionalOnClass(CqlSession.class)
@ConditionalOnProperty(name = "spring.data.cassandra.create-keyspace", havingValue = "true")
@AutoConfigureBefore(CassandraAutoConfiguration.class)
public class CassandraCreateKeyspaceAutoConfiguration {
private static final Logger logger = LoggerFactory.getLogger(CassandraCreateKeyspaceAutoConfiguration.class);
public CassandraCreateKeyspaceAutoConfiguration(CqlSessionBuilder cqlSessionBuilder, CassandraProperties properties) {
// It's OK to mutate cqlSessionBuilder because it has prototype scope.
try (CqlSession session = cqlSessionBuilder.withKeyspace((CqlIdentifier) null).build()) {
logger.info("Creating keyspace {} ...", properties.getKeyspaceName());
session.execute(CreateKeyspaceCqlGenerator.toCql(
CreateKeyspaceSpecification.createKeyspace(properties.getKeyspaceName()).ifNotExists()));
}
}
}
就我而言,我还添加了一个配置属性来控制创建, spring.data.cassandra.create-keyspace
,如果您不需要灵活性,可以将其省略。
请注意, spring-boot
自动配置取决于某些配置属性,这是我在开发环境中的配置:
spring:
data:
cassandra:
keyspace-name: mykeyspace
contact-points: 127.0.0.1
port: 9042
local-datacenter: datacenter1
schema-action: CREATE_IF_NOT_EXISTS
create-keyspace: true
更多细节: spring-boot 和 Cassandra
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.