Skip to content

Instantly share code, notes, and snippets.

@atishn
Created December 26, 2016 19:31
Show Gist options
  • Save atishn/8b4d7733524b37f0b2f0136acab2075a to your computer and use it in GitHub Desktop.
Save atishn/8b4d7733524b37f0b2f0136acab2075a to your computer and use it in GitHub Desktop.
@Component
@Service
public class CacheServiceImpl implements CacheService {
@Override
public void addToCache(final String cacheName, final String itemId, final Object item) {
// Do not save any null key or item
if (!contains(itemId, "null") && item != null) {
Ehcache cache = cacheManager.getEhcache(cacheName);
if (cache != null) {
Element element = new Element(itemId, item);
cache.put(element);
}
}
}
@Override
public Object getFromCache(final String cacheName, final String itemId) {
Ehcache cache = cacheManager.getEhcache(cacheName);
Object response = null;
if (cache != null) {
Element element = cache.get(itemId);
if (element != null) {
response = element.getObjectValue();
}
}
return response;
}
@Override
public <T> Option<T> getFromCache(final Class<T> expectedType, final String cacheName, final String id) {
Object item = getFromCache(cacheName, id);
return Option.of(item).filter(expectedType::isInstance).map(expectedType::cast);
}
@Override
public void cleanCache(final String cacheName) {
Ehcache cache = cacheManager.getEhcache(cacheName);
cache.removeAll();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment