Example usage for com.google.common.cache CacheBuilder from

List of usage examples for com.google.common.cache CacheBuilder from

Introduction

In this page you can find the example usage for com.google.common.cache CacheBuilder from.

Prototype

@GwtIncompatible("To be supported")
public static CacheBuilder<Object, Object> from(String spec) 

Source Link

Document

Constructs a new CacheBuilder instance with the settings specified in spec .

Usage

From source file:com.thinkbiganalytics.auth.cache.UserCacheAuthConfig.java

@Bean(name = "loginPrincipalCache")
public Cache<Principal, Set<Principal>> principalCache() {
    CacheBuilder<Object, Object> builder = CacheBuilder.from(cacheSpec);
    return builder.build();
}

From source file:com.digitalpebble.storm.crawler.persistence.AbstractStatusUpdaterBolt.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from  www.  ja  va 2  s . c  o  m*/
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
    _collector = collector;

    scheduler = new DefaultScheduler();
    scheduler.init(stormConf);
    mdTransfer = MetadataTransfer.getInstance(stormConf);

    useCache = ConfUtils.getBoolean(stormConf, useCacheParamName, true);

    if (useCache) {
        String spec = "maximumSize=10000,expireAfterAccess=1h";
        spec = ConfUtils.getString(stormConf, cacheConfigParamName, spec);
        cache = CacheBuilder.from(spec).build();
    }
}

From source file:com.scurrilous.circe.impl.GuavaHashCache.java

/**
 * Constructs a new {@link GuavaHashCache}.
 *//*from www .j a  va 2 s. c  o m*/
public GuavaHashCache() {
    String cacheSpec;
    try {
        cacheSpec = System.getProperty(GuavaHashCache.class.getName() + ".cacheSpec");
    } catch (final SecurityException e) {
        cacheSpec = null;
    }

    final CacheBuilder<Object, Object> cacheBuilder;
    if (cacheSpec != null)
        cacheBuilder = CacheBuilder.from(cacheSpec);
    else
        cacheBuilder = CacheBuilder.newBuilder().initialCapacity(4).concurrencyLevel(1).softValues();
    cache = cacheBuilder.build();
}

From source file:com.digitalpebble.stormcrawler.persistence.AbstractStatusUpdaterBolt.java

@SuppressWarnings({ "unchecked", "rawtypes" })
@Override/*from  w  w  w .ja va 2s.  co  m*/
public void prepare(Map stormConf, TopologyContext context, OutputCollector collector) {
    _collector = collector;

    scheduler = Scheduler.getInstance(stormConf);

    mdTransfer = MetadataTransfer.getInstance(stormConf);

    useCache = ConfUtils.getBoolean(stormConf, useCacheParamName, true);

    if (useCache) {
        String spec = ConfUtils.getString(stormConf, cacheConfigParamName);
        cache = CacheBuilder.from(spec).build();

        context.registerMetric("cache size", new IMetric() {
            @Override
            public Object getValueAndReset() {
                return cache.size();
            }
        }, 30);
    }

    maxFetchErrors = ConfUtils.getInt(stormConf, maxFetchErrorsParamName, 3);
}

From source file:org.jooby.hbs.Hbs.java

@Override
public void configure(final Env mode, final Config config, final Binder binder) {

    // cache/*from   ww  w .  j  a  va2  s.  c om*/
    if ("dev".equals(mode.name()) || config.getString("hbs.cache").isEmpty()) {
        // noop cache
        hbs.with(NullTemplateCache.INSTANCE);
    } else {
        hbs.with(new GuavaTemplateCache(CacheBuilder.from(config.getString("hbs.cache")).build()));
    }

    binder.bind(Handlebars.class).toInstance(hbs);
    Engine engine = new Engine(hbs);

    Multibinder.newSetBinder(binder, Body.Formatter.class).addBinding().toInstance(engine);

    // direct accessf
    binder.bind(Key.get(View.Engine.class, Names.named(engine.name()))).toInstance(engine);
}

From source file:ome.services.blitz.util.ParamsCache.java

public ParamsCache(Registry reg, Roles roles, ScriptRepoHelper scripts, String spec) {
    this.reg = reg;
    this.roles = roles;
    this.scripts = scripts;
    this.cache = CacheBuilder.from(spec).build(new CacheLoader<Key, JobParams>() {
        public JobParams load(Key key) throws Exception {
            return lookup(key);
        }/*  w ww.j  a  va 2  s. c o m*/
    });
}

From source file:eionet.webq.cache.GuavaCacheManager.java

/**
 * Set the Guava CacheBuilderSpec to use for building each individual
 * {@link GuavaCache} instance./*w w w  .j a v a  2  s. c  o m*/
 *
 * @see #createNativeGuavaCache
 * @see com.google.common.cache.CacheBuilder#from(CacheBuilderSpec)
 */
public void setCacheBuilderSpec(CacheBuilderSpec cacheBuilderSpec) {
    this.cacheBuilder = CacheBuilder.from(cacheBuilderSpec);
}

From source file:com.heliosapm.opentsdb.client.opentsdb.OTMetricCache.java

/**
 * Creates a new OTMetricCache/*from w ww. jav  a  2 s . c  o m*/
 */
private OTMetricCache() {
    log = LogManager.getLogger(getClass());
    OBJECT_NAME = Util.objectName(Util.getJMXDomain() + ":service=OTMetricCache");
    CacheBuilderSpec spec = null;
    String cacheSpec = ConfigurationReader.conf(Constants.PROP_OTMETRIC_CACHE_SPEC,
            Constants.DEFAULT_OTMETRIC_CACHE_SPEC);
    try {
        spec = CacheBuilderSpec.parse(cacheSpec);
    } catch (Exception ex) {
        log.warn("Invalid Cache Spec [{}]. Reverting to default: [{}]", cacheSpec,
                Constants.DEFAULT_OTMETRIC_CACHE_SPEC);
        cacheSpec = Constants.DEFAULT_OTMETRIC_CACHE_SPEC;
        spec = CacheBuilderSpec.parse(cacheSpec);
    }
    //      loader = new CacheLoader<String, OTMetric>() {
    //         @Override
    //         public OTMetric load(String key) throws Exception {            
    //            return new OTMetric(key);
    //         }
    //      };
    cache = CacheBuilder.from(spec).removalListener(this).build();
    if (cacheSpec.contains("recordStats")) {
        OTMetricCacheStats stats = new OTMetricCacheStats(cache);
        try {
            Util.registerMBean(stats, OBJECT_NAME);
        } catch (Exception ex) {
            log.warn("Failed to register OTMetricCacheStats. Will Continue without");
        }
    }
}

From source file:ca.exprofesso.guava.jcache.GuavaCache.java

public GuavaCache(String cacheName, CompleteConfiguration<K, V> configuration, CacheManager cacheManager) {
    this.cacheName = cacheName;
    this.configuration = configuration;
    this.cacheManager = cacheManager;

    String properties = cacheManager.getProperties().toString();

    CacheBuilderSpec cacheBuilderSpec = CacheBuilderSpec
            .parse(properties.substring(1, properties.length() - 1));

    CacheBuilder cacheBuilder = CacheBuilder.from(cacheBuilderSpec);

    ExpiryPolicy expiryPolicy = configuration.getExpiryPolicyFactory().create();

    if (expiryPolicy instanceof ModifiedExpiryPolicy) // == Guava expire after write
    {//from w  ww  .j  a va  2s .c om
        Duration d = expiryPolicy.getExpiryForUpdate();

        cacheBuilder.expireAfterWrite(d.getDurationAmount(), d.getTimeUnit());
    } else if (expiryPolicy instanceof TouchedExpiryPolicy) // == Guava expire after access
    {
        Duration d = expiryPolicy.getExpiryForAccess();

        cacheBuilder.expireAfterAccess(d.getDurationAmount(), d.getTimeUnit());
    }

    this.cacheEntryListenerConfigurations = Sets
            .newHashSet(configuration.getCacheEntryListenerConfigurations());

    if (!this.cacheEntryListenerConfigurations.isEmpty()) {
        cacheBuilder = cacheBuilder.removalListener(this);
    }

    if (configuration.isManagementEnabled()) {
        GuavaCacheMXBean bean = new GuavaCacheMXBean(this);

        try {
            ManagementFactory.getPlatformMBeanServer().registerMBean(bean,
                    new ObjectName(bean.getObjectName()));
        } catch (OperationsException | MBeanException e) {
            throw new CacheException(e);
        }
    }

    if (configuration.isStatisticsEnabled()) {
        GuavaCacheStatisticsMXBean bean = new GuavaCacheStatisticsMXBean(this);

        try {
            ManagementFactory.getPlatformMBeanServer().registerMBean(bean,
                    new ObjectName(bean.getObjectName()));
        } catch (OperationsException | MBeanException e) {
            throw new CacheException(e);
        }

        cacheBuilder.recordStats();
    }

    if (configuration.isReadThrough()) {
        Factory<CacheLoader<K, V>> factory = configuration.getCacheLoaderFactory();

        this.cache = (Cache<K, V>) cacheBuilder.build(new GuavaCacheLoader<>(factory.create()));
    } else {
        this.cache = (Cache<K, V>) cacheBuilder.build();
    }

    this.view = cache.asMap();
}

From source file:org.springframework.cache.guava.GuavaCacheManager.java

/**
 * Set the Guava CacheBuilderSpec to use for building each individual
 * {@link GuavaCache} instance.// ww  w.j a v  a 2s  .com
 * @see #createNativeGuavaCache
 * @see com.google.common.cache.CacheBuilder#from(CacheBuilderSpec)
 */
public void setCacheBuilderSpec(CacheBuilderSpec cacheBuilderSpec) {
    doSetCacheBuilder(CacheBuilder.from(cacheBuilderSpec));
}