Using Spring Batch to write to a Cassandra Databas

2019-04-11 19:17发布

问题:

As of now, I'm able to connect to Cassandra via the following code:

import com.datastax.driver.core.Cluster;
import com.datastax.driver.core.Session;

public static Session connection() {
    Cluster cluster = Cluster.builder()
        .addContactPoints("IP1", "IP2")
        .withCredentials("user", "password")
        .withSSL()
        .build();
    Session session = null;
    try {
        session = cluster.connect("database_name");
        session.execute("CQL Statement");
    } finally {
        IOUtils.closeQuietly(session);
        IOUtils.closeQuietly(cluster);
    }
    return session;
}

The problem is that I need to write to Cassandra in a Spring Batch project. Most of the starter kits seem to use a JdbcBatchItemWriter to write to a mySQL database from a chunk. Is this possible? It seems that a JdbcBatchItemWriter cannot connect to a Cassandra database.

The current itemwriter code is below:

@Bean
public JdbcBatchItemWriter<Person> writer() {
    JdbcBatchItemWriter<Person> writer = new JdbcBatchItemWriter<Person>();
    writer.setItemSqlParameterSourceProvider(new 
        BeanPropertyItemSqlParameterSourceProvider<Person>());
    writer.setSql("INSERT INTO people (first_name, last_name) VALUES 
        (:firstName, :lastName)");
    writer.setDataSource(dataSource);
    return writer;
}

回答1:

Spring Data Cassandra provides repository abstractions for Cassandra that you should be able to use in conjunction with the RepositoryItemWriter to write to Cassandra from Spring Batch.