【问题标题】:How to give ttl in Cassandra when inserting data in batches?批量插入数据时如何在Cassandra中给出ttl?
【发布时间】:2019-10-02 07:38:44
【问题描述】:

您好,我正在使用 Cassandra 来保存用户数据。我只想将用户的数据存储 24 小时,所以我给 ttl 24 小时。对于每个用户,有多个条目。所以我想为每个用户批量插入数据,而不是多次调用数据库。我正在使用 Cassandra 操作来提供 ttl 。我可以为单条记录提供 ttl 。批量插入数据时如何提供ttl

public class CustomizedUserFeedRepositoryImpl<T> implements CustomizedUserFeedRepository<T> {


private CassandraOperations cassandraOperations;

@Autowired
CustomizedUserFeedRepositoryImpl(CassandraOperations cassandraOperations){
    this.cassandraOperations = cassandraOperations;

}

@Override
public <S extends T> S save(S entity, int ttl){
    InsertOptions insertOptions;
    if(ttl == 0) {
        insertOptions =  InsertOptions.builder().ttl(Duration.ofHours(24)).build();
    } else {
        insertOptions = InsertOptions.builder().ttl(ttl).build();
    }
    cassandraOperations.insert(entity,insertOptions);
    return entity;
}

@Override
public void saveAllWithTtl(java.lang.Iterable<T> entities, int ttl){
    entities.forEach(entity->{
        save(entity,ttl);
    });
}

}

如您所见,我必须遍历列表 make 并为每条记录进行数据库调用。批处理操作 cassandraOperations.batchOps().insert() 只需要 list of objects 。使用 batchops() 函数时如何为每条记录设置 ttl ?

【问题讨论】:

  • 您是插入到同一个分区还是多个分区?
  • 在同一个分区上,因为用户 id 是分区键

标签: spring-boot cassandra


【解决方案1】:
   /**
     * Add a collection of inserts with given {@link WriteOptions} to the batch.
     *
     * @param entities the entities to insert; must not be {@literal null}.
     * @param options the WriteOptions to apply; must not be {@literal null}.
     * @return {@code this} {@link CassandraBatchOperations}.
     * @throws IllegalStateException if the batch was already executed.
     * @since 2.0
     */
    CassandraBatchOperations insert(Iterable<?> entities, WriteOptions options);

你可以使用insert(Iterable&lt;?&gt; entities, WriteOptions options)方法

@EqualsAndHashCode(callSuper = true)
public class WriteOptions extends QueryOptions {

private static final WriteOptions EMPTY = new WriteOptionsBuilder().build();

private final Duration ttl;
private final @Nullable Long timestamp;

batchOperations.insert(entity, WriteOptions.builder().ttl(20).build());

【讨论】:

    猜你喜欢
    • 2019-03-25
    • 2014-04-13
    • 2011-07-03
    • 1970-01-01
    • 1970-01-01
    • 2018-06-08
    • 2019-09-22
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多