-
Notifications
You must be signed in to change notification settings - Fork 2
SimpleCache
A SimpleCache is a cache that stores all the data in redis, having none to little data in local.
If some processes/threads use SimpleCache with the same name, they all retrieve the same data from redis.
No data nor keys can be null, and all data must have and expiration time
To create/use a simple cache, you give a name and a deault timeout (in ms) for the data
SimpleCache myCache = new SimpleCache(jedisPool, "myCache", 5000);
Or you can have a cache loader in case the data is not in redis, it retrieves from external sources and stores it in redis cache.
SimpleCache myCache = new SimpleCache(jedisPool, "myCache", 5000, key -> {
Document document = myDocumentDAO.getDocumentById(key);
return document.toJSON();
});
Retrieve your data from the cache
simpleCache.get("myKey");
Retrieve your data from the cache with custom loader
simpleCache.get("myKey", key -> {
Document document = myExternalDocumentLoader.getDocumentById(key);
return document.toJSON();
});
Even if a general loader is defined in the constructor or with the cache.withCacheLoader() method, the custom one in the get method will be used.
We call read-through when the value is recovered from external database if needed when accesing it.
Store data in cache
simpleCache.put("myKey", "myDocument");
Store data in cache with custom timeout
simpleCache.put("myKey", "myDocument", 7500);
You can define a CacheWriter to the cache. When a new value is stored in cache, it can be stored in external database. When a key is deleted from cache, a it can be deleted from external database. This is called cache write-through.
SimpleCache myCache = new SimpleCache(jedisPool, "myCache", 5000);
myCache.withCacheWriter(new CacheWriter() {
@Override
public void write(String key, String value) {
myDocumentDAO.save(Document.fromJSON(value));
}
@Override
public void delete(String key) {
myDocumentDAO.remove(key);
}
}
There are a lot of options avalible !