Skip to content

Instantly share code, notes, and snippets.

@abhin4v
Last active February 4, 2020 11:45
Show Gist options
  • Save abhin4v/5516340 to your computer and use it in GitHub Desktop.
Save abhin4v/5516340 to your computer and use it in GitHub Desktop.
An implementation of the Spring Cache interface on top of Google Guava cache
import java.util.List;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.cache.Cache;
import org.springframework.cache.support.SimpleValueWrapper;
import com.google.common.base.Optional;
import com.google.common.cache.CacheBuilder;
import com.google.common.cache.CacheBuilderSpec;
import com.google.common.collect.ImmutableList;
public class GuavaCache implements Cache {
private final Logger logger = LoggerFactory.getLogger(this.getClass());
private final com.google.common.cache.Cache<String, Optional<Object>> cache;
private final String name;
public GuavaCache(final String name,
final com.google.common.cache.Cache<String, Optional<Object>> cache) {
this.name = name;
this.cache = cache;
}
public GuavaCache(final String name, final CacheBuilderSpec cacheBuilderSpec) {
this(name, CacheBuilder.from(cacheBuilderSpec).<String, Optional<Object>>build());
}
@Override
public String getName() {
return name;
}
@Override
public Object getNativeCache() {
return cache;
}
@Override
public ValueWrapper get(final Object key) {
String fullKey = decorateKey(key);
Optional<Object> optional = cache.getIfPresent(fullKey);
if (optional != null) {
logger.trace("Cache {} hit: {}", name, fullKey);
} else {
logger.trace("Cache {} miss: {}", name, fullKey);
}
return optional == null ? null : new SimpleValueWrapper(optional.orNull());
}
@Override
public void put(final Object key, final Object value) {
String fullKey = decorateKey(key);
logger.trace("Cache {} put: {}", name, fullKey);
cache.put(fullKey, Optional.fromNullable(value));
}
@Override
public void evict(final Object key) {
String fullKey = decorateKey(key);
logger.trace("Cache {} evict: {}", name, fullKey);
cache.invalidate(fullKey);
}
@Override
public void clear() {
logger.trace("Cache {} clear", name);
cache.invalidateAll();
}
public void cleanUp () {
logger.trace("Cache {} cleanup", name);
cache.cleanUp();
}
public List<Object> values() {
return ImmutableList.copyOf(Optional.presentInstances(cache.asMap().values()));
}
// Override this method in subclasses to add custom behaviour to the cache keys
protected String decorateKey(final Object key) {
return key.toString();
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment