使用 Spring data couchbase,这是一种可以为每个文档配置 ttl 的简单方法。
public class CouchbaseConfig extends AbstractCouchbaseConfiguration {
@Override
protected List<String> bootstrapHosts() {
return Arrays.asList("localhost");
}
@Override
protected String getBucketName() {
return "default";
}
@Override
protected String getBucketPassword() {
return "password1";
}
@Bean
public MappingCouchbaseConverter mappingCouchbaseConverter() throws Exception {
MappingCouchbaseConverter converter = new ExpiringDocumentCouchbaseConverter(couchbaseMappingContext());
converter.setCustomConversions(customConversions());
return converter;
}
class ExpiringDocumentCouchbaseConverter extends MappingCouchbaseConverter {
/**
* Create a new {@link MappingCouchbaseConverter}.
*
* @param mappingContext the mapping context to use.
*/
public ExpiringDocumentCouchbaseConverter(MappingContext<? extends CouchbasePersistentEntity<?>, CouchbasePersistentProperty> mappingContext) {
super(mappingContext);
}
// Setting custom TTL on documents.
@Override
public void write(final Object source, final CouchbaseDocument target) {
super.write(source, target);
if (source instanceof ClassContainingTTL) {
target.setExpiration(((ClassContainingTTL) source).getTimeToLive());
}
}
}
}