Skip to content

Instantly share code, notes, and snippets.

@sizovs
Created December 1, 2014 17:48
Show Gist options
  • Save sizovs/d3b0ba4ac9db773a2e57 to your computer and use it in GitHub Desktop.
Save sizovs/d3b0ba4ac9db773a2e57 to your computer and use it in GitHub Desktop.
package fm.ask.infrastructure.caching;
import com.google.common.base.Supplier;
import com.google.common.base.Ticker;
import com.google.common.cache.CacheBuilder;
import com.rubylight.conf.IConfListener;
import com.rubylight.conf.IConfProperty;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.cache.guava.GuavaCacheManager;
import java.util.Collection;
import java.util.concurrent.TimeUnit;
import static com.google.common.base.Suppliers.memoize;
public class GuavaCacheManagerFactory extends CacheManagerFactory {
private final String[] cacheName;
private final IConfProperty<? extends CacheConfiguration> cacheConfiguration;
private final Ticker ticker;
public GuavaCacheManagerFactory(IConfProperty<? extends CacheConfiguration> configuration,
Ticker ticker, String... cacheName) {
this.cacheName = cacheName;
this.cacheConfiguration = configuration;
this.ticker = ticker;
}
@Override
protected CacheManager createInstance() {
// CacheManager initializes too early. At this stage we cannot access configuration, hence lazy loading.
return new MemoizingCacheManager();
}
private class MemoizingCacheManager implements CacheManager {
private final Supplier<CacheManager> cacheMemoizer = memoize(new CacheManagerSupplier());
private class CacheManagerSupplier implements Supplier<CacheManager> {
@Override
public CacheManager get() {
final GuavaCacheManager cacheManager = new GuavaCacheManager(cacheName);
refreshConfiguration(cacheManager);
cacheConfiguration.addPropertyListener(new IConfListener() {
@Override
public void changeProperty(String propertyKey) {
refreshConfiguration(cacheManager);
}
});
return cacheManager;
}
private void refreshConfiguration(GuavaCacheManager cacheManager) {
long ttl = cacheConfiguration.getPropertyValue().getTtl();
long size = cacheConfiguration.getPropertyValue().getSize();
cacheManager.setCacheBuilder(CacheBuilder.newBuilder()
.ticker(ticker)
.maximumSize(size)
.expireAfterWrite(ttl, TimeUnit.SECONDS));
}
}
@Override
public Cache getCache(String name) {
return cacheMemoizer.get().getCache(name);
}
@Override
public Collection<String> getCacheNames() {
return cacheMemoizer.get().getCacheNames();
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment