Using Spring Batch to write to a Cassandra Database

后端 未结 2 1194
[愿得一人]
[愿得一人] 2021-01-06 16:08

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;

publi         


        
相关标签:
2条回答
  • 2021-01-06 16:12

    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.

    0 讨论(0)
  • 2021-01-06 16:17

    It is possible to extend Spring Batch to support Cassandra by customising ItemReader and ItemWriter.

    ItemWriter example:

    public class CassandraBatchItemWriter<Company> implements ItemWriter<Company>, InitializingBean {
    
        protected static final Log logger = LogFactory.getLog(CassandraBatchItemWriter.class);
        private final Class<Company> aClass;
        @Autowired
        private CassandraTemplate cassandraTemplate;
    
        @Override
        public void afterPropertiesSet() throws Exception { }
    
        public CassandraBatchItemWriter(final Class<Company> aClass) {
            this.aClass = aClass;
        }
    
        @Override
        public void write(final List<? extends Company> items) throws Exception {
            logger.debug("Write operations is performing, the size is {}" + items.size());
            if (!items.isEmpty()) {
                logger.info("Deleting in a batch performing...");
                cassandraTemplate.deleteAll(aClass);
                logger.info("Inserting in a batch performing...");
                cassandraTemplate.insert(items);
            }
    
            logger.debug("Items is null...");
        }
    }
    

    Then you can inject it as a @Bean through @Configuration

    @Bean
    public ItemWriter<Company> writer(final DataSource dataSource) {
        final CassandraBatchItemWriter<Company> writer = new CassandraBatchItemWriter<Company>(Company.class);
        return writer;
    }
    

    Full source code can be found in Github repo: Spring-Batch-with-Cassandra

    0 讨论(0)
提交回复
热议问题