您好,我正在使用 Cassandra 来保存用户数据。我只想将用户的数据存储 24 小时,所以我提供了 24 小时的 ttl。对于每个用户,有多个条目。所以我想为每个用户批量插入数据,而不是多次调用数据库。我正在使用 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() 只接受对象列表。使用 batchops() 功能时如何为每条记录设置 ttl ?
/**
* 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<?> 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());
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句