Persistence API
The Persistence API provides an easy and fast way to store data. It supports two main storages, namely PersistentSequence and PersistentQueue.
PersistentSequence
PersistentSequence provides a functionality for storing sequential data (for example, logs). Each record should have a unique index. Indexer implementation is used to provide an index for a certain storing record. Also, PersistentSequence requires custom Serializer implementation to serialize objects to byte buffer and restore them back.
PersistenceFactory factory = ...
Indexer<MyRecord> indexer = new Indexer<MyRecord>() {
@Override
public long getIndex(MyRecord item) {
return item.getId();
}
};
Serializer<MyRecord> serializer = new Serializer<MyRecord>() {
@Override
public void serialize(MyRecord item, ElasticByteBuffer buffer) {
// serialize instance ...
}
@Override
public MyRecord deserialize(ElasticByteBuffer buffer, int length) {
MyRecord record = new MyRecord;
// load data to instance...
return record;
}
};
final PersistentSequence<MyRecord> sequence = factory.buildSequence("seq_sample", indexer, serializer);
//store record to sequence
sequence.append(record);
In addition to storing data, PersistentSequence provides methods for retrieving records from storage. It supports reading a single item by index or iterating through items:
//get single item with index 100
final MyRecord myRecord = sequence.get(100);
//iterate items from index 0 till 100
sequence.retrieveItems(0, 100, new RetrieveSequenceItemsListener<MyRecord>() {
@Override
public void onItem(long id, MyRecord record) {
//...
}
}, true);
There is a possibility to review stored records and remove some of them from storage:
sequence.cleanUp(new CleanupItemListener<MyRecord>() {
@Override
public boolean checkForClean(long id, MyRecord item) {
//return true to removed this record from storage
return false;
}
});
Or remove all and reset the sequence:
//remove all items and reset index sequence.reset();
The default PersistentSequence implementation is optimized for writing data, so reading operations may take a bit more time.
PersistentQueue
PersistentQueue works like a queue but persists all items to the disk. Thus, it can restore its state after application restart. PersistentQueue has methods similar to java.util.Queue:
final PersistentQueue<MyRecord> queue = factory.buildQueue("queue_sample", serializer);
//push item to the tail of queue
queue.add(record);
// read iem from head but doesn't remove
record = queue.peek();
// extract item from head and remove it from queue
record = queue.poll();
Also PersistentQueue allows iterating all its items:
queue.iterate(new RetrieveQueueItemsListener<MyRecord>() {
@Override
public void onItem(MyRecord record) {
//....
}
});
To remove all the items from the queue, you can use the clean method:
//remove all items and clean file queue.clear();