Using Spring Batch to write to a Cassandra Database

后端 未结 2 1212
[愿得一人]
[愿得一人] 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:17

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

    ItemWriter example:

    public class CassandraBatchItemWriter implements ItemWriter, InitializingBean {
    
        protected static final Log logger = LogFactory.getLog(CassandraBatchItemWriter.class);
        private final Class aClass;
        @Autowired
        private CassandraTemplate cassandraTemplate;
    
        @Override
        public void afterPropertiesSet() throws Exception { }
    
        public CassandraBatchItemWriter(final Class aClass) {
            this.aClass = aClass;
        }
    
        @Override
        public void write(final List 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 writer(final DataSource dataSource) {
        final CassandraBatchItemWriter writer = new CassandraBatchItemWriter(Company.class);
        return writer;
    }
    

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

提交回复
热议问题