Java Code Examples for com.google.common.cache.CacheBuilder#expireAfterAccess()

The following examples show how to use com.google.common.cache.CacheBuilder#expireAfterAccess() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: TransformXml.java    From localization_nifi with Apache License 2.0 7 votes vote down vote up
@OnScheduled
public void onScheduled(final ProcessContext context) {
    final ComponentLog logger = getLogger();
    final Integer cacheSize = context.getProperty(CACHE_SIZE).asInteger();
    final Long cacheTTL = context.getProperty(CACHE_TTL_AFTER_LAST_ACCESS).asTimePeriod(TimeUnit.SECONDS);

    if (cacheSize > 0) {
        CacheBuilder cacheBuilder = CacheBuilder.newBuilder().maximumSize(cacheSize);
        if (cacheTTL > 0) {
            cacheBuilder = cacheBuilder.expireAfterAccess(cacheTTL, TimeUnit.SECONDS);
        }

        cache = cacheBuilder.build(
           new CacheLoader<String, Templates>() {
               public Templates load(String path) throws TransformerConfigurationException {
                   return newTemplates(path);
               }
           });
    } else {
        cache = null;
        logger.warn("Stylesheet cache disabled because cache size is set to 0");
    }
}
 
Example 2
Source File: GuavaCache.java    From Mybatis-PageHelper with MIT License 6 votes vote down vote up
public GuavaCache(Properties properties, String prefix) {
    CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
    String maximumSize = properties.getProperty(prefix + ".maximumSize");
    if (StringUtil.isNotEmpty(maximumSize)) {
        cacheBuilder.maximumSize(Long.parseLong(maximumSize));
    } else {
        cacheBuilder.maximumSize(1000);
    }
    String expireAfterAccess = properties.getProperty(prefix + ".expireAfterAccess");
    if (StringUtil.isNotEmpty(expireAfterAccess)) {
        cacheBuilder.expireAfterAccess(Long.parseLong(expireAfterAccess), TimeUnit.MILLISECONDS);
    }
    String expireAfterWrite = properties.getProperty(prefix + ".expireAfterWrite");
    if (StringUtil.isNotEmpty(expireAfterWrite)) {
        cacheBuilder.expireAfterWrite(Long.parseLong(expireAfterWrite), TimeUnit.MILLISECONDS);
    }
    String initialCapacity = properties.getProperty(prefix + ".initialCapacity");
    if (StringUtil.isNotEmpty(initialCapacity)) {
        cacheBuilder.initialCapacity(Integer.parseInt(initialCapacity));
    }
    CACHE = cacheBuilder.build();
}
 
Example 3
Source File: DynamicRanker.java    From elasticsearch-dynarank with Apache License 2.0 6 votes vote down vote up
@Inject
public DynamicRanker(final Settings settings, final Client client, final ClusterService clusterService,
        final ScriptService scriptService, final ThreadPool threadPool, final ActionFilters filters,
        final NamedWriteableRegistry namedWriteableRegistry) {
    this.client = client;
    this.clusterService = clusterService;
    this.scriptService = scriptService;
    this.threadPool = threadPool;
    this.namedWriteableRegistry = namedWriteableRegistry;

    logger.info("Initializing DynamicRanker");

    final TimeValue expire = SETTING_DYNARANK_CACHE_EXPIRE.get(settings);
    cleanInterval = SETTING_DYNARANK_CACHE_CLEAN_INTERVAL.get(settings);

    final CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder().concurrencyLevel(16);
    if (expire.millis() >= 0) {
        builder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS);
    }
    scriptInfoCache = builder.build();
}
 
Example 4
Source File: NetflowV9Decoder.java    From datacollector with Apache License 2.0 6 votes vote down vote up
public static Cache<FlowSetTemplateCacheKey, FlowSetTemplate> buildTemplateCache(
    int maxTemplateCacheSize,
    int templateCacheTimeoutMs
) {
  CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
  if (maxTemplateCacheSize > 0) {
    cacheBuilder = cacheBuilder.maximumSize(maxTemplateCacheSize);
  }
  if (templateCacheTimeoutMs > 0) {
    cacheBuilder = cacheBuilder.expireAfterAccess(templateCacheTimeoutMs, TimeUnit.MILLISECONDS);
  }
  if (LOG.isTraceEnabled()) {
    cacheBuilder = cacheBuilder.removalListener((notification) -> LOG.trace(
        "Removing flow set template entry {} for cause: {} ",
        notification.getKey(),
        notification.getCause()
    ));
  }
  return cacheBuilder.build();
}
 
Example 5
Source File: CachingTableProvider.java    From samza with Apache License 2.0 6 votes vote down vote up
private ReadWriteTable createDefaultCacheTable(String tableId, JavaTableConfig tableConfig) {
  long readTtlMs = Long.parseLong(tableConfig.getForTable(tableId, CachingTableDescriptor.READ_TTL_MS, "-1"));
  long writeTtlMs = Long.parseLong(tableConfig.getForTable(tableId, CachingTableDescriptor.WRITE_TTL_MS, "-1"));
  long cacheSize = Long.parseLong(tableConfig.getForTable(tableId, CachingTableDescriptor.CACHE_SIZE, "-1"));

  CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
  if (readTtlMs != -1) {
    cacheBuilder.expireAfterAccess(readTtlMs, TimeUnit.MILLISECONDS);
  }
  if (writeTtlMs != -1) {
    cacheBuilder.expireAfterWrite(writeTtlMs, TimeUnit.MILLISECONDS);
  }
  if (cacheSize != -1) {
    cacheBuilder.maximumSize(cacheSize);
  }

  logger.info(String.format("Creating default cache with: readTtl=%d, writeTtl=%d, maxSize=%d",
      readTtlMs, writeTtlMs, cacheSize));

  GuavaCacheTable cacheTable = new GuavaCacheTable(tableId + "-def-cache", cacheBuilder.build());
  cacheTable.init(this.context);

  return cacheTable;
}
 
Example 6
Source File: GuavaCacheFactoryBean.java    From spring-cache-demo with GNU General Public License v2.0 6 votes vote down vote up
@Override
public void afterPropertiesSet() {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    if (maximumSize != null) {
      builder.maximumSize(maximumSize);
    }
    if (expireAfterAccessInSeconds != null) {
      builder.expireAfterAccess(expireAfterAccessInSeconds, TimeUnit.SECONDS);
    }
    if (expireAfterWriteInSeconds != null) {
      builder.expireAfterWrite(expireAfterWriteInSeconds, TimeUnit.SECONDS);
    }
    
    com.google.common.cache.Cache<Object, Object> guavaCache= builder.build();
    this.cache = new GuavaCache(this.name, guavaCache, this.allowNullValues);
}
 
Example 7
Source File: TransformXml.java    From nifi with Apache License 2.0 6 votes vote down vote up
@OnScheduled
public void onScheduled(final ProcessContext context) {
    final ComponentLog logger = getLogger();
    final Integer cacheSize = context.getProperty(CACHE_SIZE).asInteger();
    final Long cacheTTL = context.getProperty(CACHE_TTL_AFTER_LAST_ACCESS).asTimePeriod(TimeUnit.SECONDS);

    if (cacheSize > 0) {
        CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder().maximumSize(cacheSize);
        if (cacheTTL > 0) {
            cacheBuilder = cacheBuilder.expireAfterAccess(cacheTTL, TimeUnit.SECONDS);
        }

        cache = cacheBuilder.build(
                new CacheLoader<String, Templates>() {
                    @Override
                    public Templates load(String path) throws TransformerConfigurationException, LookupFailureException {
                        return newTemplates(context, path);
                    }
                });
    } else {
        cache = null;
        logger.info("Stylesheet cache disabled because cache size is set to 0");
    }
}
 
Example 8
Source File: LoadingCacheHelper.java    From spring-microservice-exam with MIT License 6 votes vote down vote up
/**
 * 初始化loadingCache
 * @param clazz clazz
 * @param refreshAfterWriteDuration 单位秒
 * @param expireAfterAccessDuration 单位秒
 * @param <K> key
 * @param <V> value
 * @param cacheSize cacheSize
 * @return LoadingCache
 */
private <K, V> LoadingCache<K, V> initLoadingCache(Class<? extends CacheLoader<K, V>> clazz,
		long refreshAfterWriteDuration, long expireAfterAccessDuration, long cacheSize) {
	try {
		log.info("Instantiating LoadingCache: {}", clazz);
		CacheLoader<K, V> cacheLoader = clazz.newInstance();
		CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
		builder.concurrencyLevel(1);
		if (expireAfterAccessDuration > 0) {
			// 在给定时间内没有被读/写访问,则回收
			builder.expireAfterAccess(expireAfterAccessDuration, TimeUnit.SECONDS);
		} else {
			// 自动刷新
			builder.refreshAfterWrite(refreshAfterWriteDuration, TimeUnit.SECONDS);
		}
		if (cacheSize > 0)
			builder.maximumSize(cacheSize);
		LoadingCache<K, V> cache = builder.build(cacheLoader);
		this.loadingCacheMap.put(clazz.getSimpleName(), cache);
		return cache;
	} catch (Exception e) {
		log.error("Error Instantiating LoadingCache: " + clazz, e);
		throw new CommonException(e, "Error Instantiating LoadingCache: " + clazz);
	}
}
 
Example 9
Source File: TenantCacheImpl.java    From phoenix with Apache License 2.0 6 votes vote down vote up
private Cache<ImmutableBytesPtr, CacheEntry> buildCache(final int ttl, final boolean isPersistent) {
    CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder();
    if (isPersistent) {
        builder.expireAfterWrite(ttl, TimeUnit.MILLISECONDS);
    } else {
        builder.expireAfterAccess(ttl, TimeUnit.MILLISECONDS);
    }
    return builder
        .ticker(getTicker())
        .removalListener(new RemovalListener<ImmutableBytesPtr, CacheEntry>(){
            @Override
            public void onRemoval(RemovalNotification<ImmutableBytesPtr, CacheEntry> notification) {
                if (isPersistent || !notification.getValue().getUsePersistentCache()) {
                    Closeables.closeAllQuietly(Collections.singletonList(notification.getValue()));
                }
            }
        })
        .build();
}
 
Example 10
Source File: UsageTrackingCache.java    From docker-plugin with MIT License 6 votes vote down vote up
/**
 * Full constructor.
 * 
 * @param duration
 *            How long inactive things should be kept in the cache.
 * @param unit
 *            The <code>duration</code>'s unit of measurement.
 * @param expiryHandler
 *            Callback that is given all expired values from the cache just
 *            before they are thrown away.
 */
UsageTrackingCache(final long duration, @Nonnull final TimeUnit unit,
        @Nonnull final ExpiryHandler<K, V> expiryHandler) {
    activeCacheByKey = new HashMap<>();
    activeCacheByValue = new IdentityHashMap();
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    cacheBuilder = cacheBuilder.expireAfterAccess(duration, unit);
    final RemovalListener removalHandler = new RemovalListener<K, CacheEntry<K, V>>() {
        @Override
        public void onRemoval(RemovalNotification<K, CacheEntry<K, V>> notification) {
            final K key = notification.getKey();
            if (!activeCacheByKey.containsKey(key)) {
                final CacheEntry<K, V> record = notification.getValue();
                final V value = record.getValue();
                expiryHandler.entryDroppedFromCache(key, value);
            }
        }
    };
    cacheBuilder = cacheBuilder.removalListener(removalHandler);
    durationCache = cacheBuilder.build();
}
 
Example 11
Source File: HotKeyListener.java    From EVCache with Apache License 2.0 5 votes vote down vote up
private Cache<String, Integer> getCache(String appName) {

    	Property<Boolean> throttleFlag = throttleMap.get(appName);
        if(throttleFlag == null) {
        	throttleFlag = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheThrottler." + appName + ".throttle.hot.keys", Boolean.class).orElse(false);
            throttleMap.put(appName, throttleFlag);
        }
        if(log.isDebugEnabled()) log.debug("Throttle hot keys : " + throttleFlag);

        if(!throttleFlag.get()) {
            return null;
        }

        Cache<String, Integer> cache = cacheMap.get(appName);
        if(cache != null) return cache;

        final Property<Integer> _cacheDuration = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheThrottler." + appName + ".inmemory.expire.after.write.duration.ms", Integer.class).orElse(10000);
        final Property<Integer> _exireAfterAccessDuration = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheThrottler." + appName + ".inmemory.expire.after.access.duration.ms", Integer.class).orElse(10000);
        final Property<Integer> _cacheSize = EVCacheConfig.getInstance().getPropertyRepository().get("EVCacheThrottler." + appName + ".inmemory.cache.size", Integer.class).orElse(100);

        CacheBuilder<Object, Object> builder = CacheBuilder.newBuilder().recordStats();
        if(_cacheSize.get() > 0) {
            builder = builder.maximumSize(_cacheSize.get());
        }
        if(_exireAfterAccessDuration.get() > 0) {
            builder = builder.expireAfterAccess(_exireAfterAccessDuration.get(), TimeUnit.MILLISECONDS);
        } else if(_cacheDuration.get() > 0) {
            builder = builder.expireAfterWrite(_cacheDuration.get(), TimeUnit.MILLISECONDS);
        }
        cache = builder.build();
        cacheMap.put(appName, cache);
        return cache;
    }
 
Example 12
Source File: IndicesRequestCache.java    From Elasticsearch with Apache License 2.0 5 votes vote down vote up
private void buildCache() {
    long sizeInBytes = MemorySizeValue.parseBytesSizeValueOrHeapRatio(size, INDICES_CACHE_QUERY_SIZE).bytes();

    CacheBuilder<Key, Value> cacheBuilder = CacheBuilder.newBuilder()
            .maximumWeight(sizeInBytes).weigher(new QueryCacheWeigher()).removalListener(this);
    cacheBuilder.concurrencyLevel(concurrencyLevel);

    if (expire != null) {
        cacheBuilder.expireAfterAccess(expire.millis(), TimeUnit.MILLISECONDS);
    }

    cache = cacheBuilder.build();
}
 
Example 13
Source File: DefaultSimpleCache.java    From alfresco-repository with GNU Lesser General Public License v3.0 5 votes vote down vote up
/**
 * Construct a cache using the specified capacity and name.
 * 
 * @param maxItems The cache capacity. 0 = use {@link #DEFAULT_CAPACITY}
 * @param useMaxItems Whether the maxItems value should be applied as a size-cap for the cache.
 * @param cacheName An arbitrary cache name.
 */
@SuppressWarnings("unchecked")
public DefaultSimpleCache(int maxItems, boolean useMaxItems, int ttlSecs, int maxIdleSecs, String cacheName)
{
    if (maxItems == 0)
    {
        maxItems = DEFAULT_CAPACITY;
    }
    else if (maxItems < 0)
    {
        throw new IllegalArgumentException("maxItems may not be negative, but was " + maxItems);
    }
    this.maxItems = maxItems;
    this.useMaxItems = useMaxItems;
    this.ttlSecs = ttlSecs;
    this.maxIdleSecs = maxIdleSecs;
    setBeanName(cacheName);
    
    // The map will have a bounded size determined by the maxItems member variable.
    @SuppressWarnings("rawtypes")
    CacheBuilder builder = CacheBuilder.newBuilder();
    
    if (useMaxItems)
    {
        builder.maximumSize(maxItems);
    }
    if (ttlSecs > 0)
    {
        builder.expireAfterWrite(ttlSecs, TimeUnit.SECONDS);
    }
    if (maxIdleSecs > 0)
    {
        builder.expireAfterAccess(maxIdleSecs, TimeUnit.SECONDS);
    }
    builder.concurrencyLevel(32);
    
    cache = (Cache<K, AbstractMap.SimpleImmutableEntry<K, V>>) builder.build();
}
 
Example 14
Source File: MetaDataVersionStampStoreStateCacheFactory.java    From fdb-record-layer with Apache License 2.0 5 votes vote down vote up
@Nonnull
@Override
public FDBRecordStoreStateCache getCache(@Nonnull FDBDatabase database) {
    CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
    if (maxSize != UNLIMITED) {
        cacheBuilder.maximumSize(maxSize);
    }
    if (expireAfterAccessMillis != UNLIMITED) {
        cacheBuilder.expireAfterAccess(expireAfterAccessMillis, TimeUnit.MILLISECONDS);
    }
    Cache<SubspaceProvider, FDBRecordStoreStateCacheEntry> cache = cacheBuilder.build();
    return new MetaDataVersionStampStoreStateCache(database, cache);
}
 
Example 15
Source File: CacheStore.java    From attic-apex-malhar with Apache License 2.0 5 votes vote down vote up
@Override
public void connect() throws IOException
{
  open = true;

  if (numInitCacheLines > maxCacheSize) {
    logger.warn("numInitCacheLines = {} is greater than maxCacheSize = {}, maxCacheSize was set to {}", numInitCacheLines,
        maxCacheSize, numInitCacheLines);
    maxCacheSize = numInitCacheLines;
  }

  CacheBuilder<Object, Object> cacheBuilder = CacheBuilder.newBuilder();
  cacheBuilder.maximumSize(maxCacheSize);

  if (entryExpiryStrategy == ExpiryType.EXPIRE_AFTER_ACCESS) {
    cacheBuilder.expireAfterAccess(entryExpiryDurationInMillis, TimeUnit.MILLISECONDS);
  } else if (entryExpiryStrategy == ExpiryType.EXPIRE_AFTER_WRITE) {
    cacheBuilder.expireAfterWrite(entryExpiryDurationInMillis, TimeUnit.MILLISECONDS);
  }
  cache = cacheBuilder.build();

  if (entryExpiryStrategy == ExpiryType.NO_EVICTION) {
    return;
  }

  this.cleanupScheduler = Executors.newScheduledThreadPool(1);
  cleanupScheduler.scheduleAtFixedRate(new Runnable()
  {
    @Override
    public void run()
    {
      cache.cleanUp();
    }
  }, cacheCleanupIntervalInMillis, cacheCleanupIntervalInMillis, TimeUnit.MILLISECONDS);
}
 
Example 16
Source File: VoiceConfig.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
public CacheBuilder cacheBuilder() {
   CacheBuilder builder = CacheBuilder.newBuilder();
   if(cacheConcurrencyLevel >= 0) { builder.concurrencyLevel(cacheConcurrencyLevel); }
   if(cacheExpireAfterAccessMs >= 0) { builder.expireAfterAccess(cacheExpireAfterAccessMs, TimeUnit.MILLISECONDS); }
   if(cacheExpireAfterWriteMs >= 0) { builder.expireAfterWrite(cacheExpireAfterWriteMs, TimeUnit.MILLISECONDS); }
   if(cacheInitialCapacity >= 0) { builder.initialCapacity(cacheInitialCapacity); }
   if(cacheMaximumSize >= 0) { builder.maximumSize(cacheMaximumSize); }
   if(cacheRefreshAfterWriteMs >= 0) { builder.refreshAfterWrite(cacheRefreshAfterWriteMs, TimeUnit.MILLISECONDS); }
   if(cacheRecordStats) { builder.recordStats(); }
   return builder;
}
 
Example 17
Source File: ScriptService.java    From Elasticsearch with Apache License 2.0 4 votes vote down vote up
@Inject
public ScriptService(Settings settings, Environment env, Set<ScriptEngineService> scriptEngines,
                     ResourceWatcherService resourceWatcherService, ScriptContextRegistry scriptContextRegistry) throws IOException {
    super(settings);
    this.parseFieldMatcher = new ParseFieldMatcher(settings);
    if (Strings.hasLength(settings.get(DISABLE_DYNAMIC_SCRIPTING_SETTING))) {
        throw new IllegalArgumentException(DISABLE_DYNAMIC_SCRIPTING_SETTING + " is not a supported setting, replace with fine-grained script settings. \n" +
                "Dynamic scripts can be enabled for all languages and all operations by replacing `script.disable_dynamic: false` with `script.inline: on` and `script.indexed: on` in elasticsearch.yml");
    }

    this.scriptEngines = scriptEngines;
    this.scriptContextRegistry = scriptContextRegistry;
    int cacheMaxSize = settings.getAsInt(SCRIPT_CACHE_SIZE_SETTING, SCRIPT_CACHE_SIZE_DEFAULT);
    TimeValue cacheExpire = settings.getAsTime(SCRIPT_CACHE_EXPIRE_SETTING, null);
    logger.debug("using script cache with max_size [{}], expire [{}]", cacheMaxSize, cacheExpire);

    this.defaultLang = settings.get(DEFAULT_SCRIPTING_LANGUAGE_SETTING, DEFAULT_LANG);

    CacheBuilder cacheBuilder = CacheBuilder.newBuilder();
    if (cacheMaxSize >= 0) {
        cacheBuilder.maximumSize(cacheMaxSize);
    }
    if (cacheExpire != null) {
        cacheBuilder.expireAfterAccess(cacheExpire.nanos(), TimeUnit.NANOSECONDS);
    }
    this.cache = cacheBuilder.removalListener(new ScriptCacheRemovalListener()).build();

    ImmutableMap.Builder<String, ScriptEngineService> enginesByLangBuilder = ImmutableMap.builder();
    ImmutableMap.Builder<String, ScriptEngineService> enginesByExtBuilder = ImmutableMap.builder();
    for (ScriptEngineService scriptEngine : scriptEngines) {
        for (String type : scriptEngine.types()) {
            enginesByLangBuilder.put(type, scriptEngine);
        }
        for (String ext : scriptEngine.extensions()) {
            enginesByExtBuilder.put(ext, scriptEngine);
        }
    }
    this.scriptEnginesByLang = enginesByLangBuilder.build();
    this.scriptEnginesByExt = enginesByExtBuilder.build();

    this.scriptModes = new ScriptModes(this.scriptEnginesByLang, scriptContextRegistry, settings);

    // add file watcher for static scripts
    scriptsDirectory = env.scriptsFile();
    if (logger.isTraceEnabled()) {
        logger.trace("Using scripts directory [{}] ", scriptsDirectory);
    }
    FileWatcher fileWatcher = new FileWatcher(scriptsDirectory);
    fileWatcher.addListener(new ScriptChangesListener());

    if (settings.getAsBoolean(SCRIPT_AUTO_RELOAD_ENABLED_SETTING, true)) {
        // automatic reload is enabled - register scripts
        resourceWatcherService.add(fileWatcher);
    } else {
        // automatic reload is disable just load scripts once
        fileWatcher.init();
    }
}
 
Example 18
Source File: GuavaUtils.java    From t-io with Apache License 2.0 4 votes vote down vote up
/**
 *
 * @param concurrencyLevel
 * @param timeToLiveSeconds 设置写缓存后过期时间(单位:秒)
 * @param timeToIdleSeconds 设置读缓存后过期时间(单位:秒)
 * @param initialCapacity
 * @param maximumSize
 * @param recordStats
 * @param removalListener
 * @return
 */
public static <K, V> LoadingCache<K, V> createLoadingCache(Integer concurrencyLevel, Long timeToLiveSeconds, Long timeToIdleSeconds, Integer initialCapacity,
        Integer maximumSize, boolean recordStats, RemovalListener<K, V> removalListener) {

	if (removalListener == null) {
		removalListener = new RemovalListener<K, V>() {
			@Override
			public void onRemoval(RemovalNotification<K, V> notification) {
				log.info(notification.getKey() + " was removed");
			}
		};
	}

	CacheBuilder<K, V> cacheBuilder = CacheBuilder.newBuilder().removalListener(removalListener);

	//设置并发级别为8,并发级别是指可以同时写缓存的线程数
	cacheBuilder.concurrencyLevel(concurrencyLevel);
	if (timeToLiveSeconds != null && timeToLiveSeconds > 0) {
		//设置写缓存后8秒钟过期
		cacheBuilder.expireAfterWrite(timeToLiveSeconds, TimeUnit.SECONDS);
	}
	if (timeToIdleSeconds != null && timeToIdleSeconds > 0) {
		//设置访问缓存后8秒钟过期
		cacheBuilder.expireAfterAccess(timeToIdleSeconds, TimeUnit.SECONDS);
	}

	//设置缓存容器的初始容量为10
	cacheBuilder.initialCapacity(initialCapacity);
	//设置缓存最大容量为100,超过100之后就会按照LRU最近最少使用算法来移除缓存项
	cacheBuilder.maximumSize(maximumSize);

	if (recordStats) {
		//设置要统计缓存的命中率
		cacheBuilder.recordStats();
	}
	//build方法中可以指定CacheLoader,在缓存不存在时通过CacheLoader的实现自动加载缓存
	LoadingCache<K, V> loadingCache = cacheBuilder.build(new CacheLoader<K, V>() {
		@Override
		public V load(K key) throws Exception {
			return null;
		}
	});
	return loadingCache;

	//		for (int i = 0; i < 20; i++)
	//		{
	//			//从缓存中得到数据,由于我们没有设置过缓存,所以需要通过CacheLoader加载缓存数据
	//			Long student = studentCache.get("p");
	//			System.out.println(student);
	//			//休眠1秒
	//			TimeUnit.SECONDS.sleep(1);
	//		}

	//		System.out.println("cache stats:");
	//最后打印缓存的命中率等 情况
	//		System.out.println(studentCache.stats().toString());
}
 
Example 19
Source File: IrisSettings.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
public static CacheBuilder<Object,Object> configurableCacheBuilder(String base, CacheBuilder<Object,Object> builder) {
   // If there is a full cache specification then that overrides everything
   String spec = IrisSettings.getStringProperty(base + ".spec", "");
   if (!spec.isEmpty()) {
      return CacheBuilder.from(spec);
   }

   CacheBuilder<Object,Object> bld = builder;
   int concurrency = IrisSettings.getIntegerProperty(base + ".concurrency", -1);
   if (concurrency > 0) {
      bld = bld.concurrencyLevel(concurrency);
   }

   long write = IrisSettings.getLongProperty(base + ".expire.write", -1L);
   if (write > 0) {
      bld = bld.expireAfterWrite(write, TimeUnit.MILLISECONDS);
   }

   long access = IrisSettings.getLongProperty(base + ".expire.access", -1L);
   if (access > 0) {
      bld = bld.expireAfterAccess(access, TimeUnit.MILLISECONDS);
   }

   long refresh = IrisSettings.getLongProperty(base + ".refresh.write", -1L);
   if (refresh > 0) {
      bld = bld.refreshAfterWrite(refresh, TimeUnit.MILLISECONDS);
   }

   int initsz = IrisSettings.getIntegerProperty(base + ".initial.capacity", -1);
   if (initsz > 0) {
      bld = bld.initialCapacity(initsz);
   }

   int maxsz = IrisSettings.getIntegerProperty(base + ".max.size", -1);
   if (maxsz > 0) {
      bld = bld.maximumSize(maxsz);
   }

   boolean soft = IrisSettings.getBooleanProperty(base + ".soft.values", false);
   if (soft) {
      bld = bld.softValues();
   }

   return bld;
}
 
Example 20
Source File: CachingSubsystemRegistry.java    From arcusplatform with Apache License 2.0 4 votes vote down vote up
/**
 * 
 */
@Inject
public CachingSubsystemRegistry(
      SubsystemFactory factory,
      PlaceDAO placeDao,
      ModelDao modelDao,
      PlacePopulationCacheManager populationCacheMgr,
      SubsystemConfig config
) {
   this.factory = factory;
   this.placeDao = placeDao;
   this.modelDao = modelDao;
   this.populationCacheMgr = populationCacheMgr;
   
   CacheBuilder<Object,Object> bld = CacheBuilder.newBuilder();
   if (config.getPlaceCacheConcurrencyLevel() > 0) {
      bld = bld.concurrencyLevel(config.getPlaceCacheConcurrencyLevel());
   }

   if (config.getPlaceCacheExpireAccessMs() > 0) {
      bld =bld.expireAfterAccess(config.getPlaceCacheExpireAccessMs(), TimeUnit.MILLISECONDS);
   }

   if (config.getPlaceCacheInitialCapacity() > 0) {
      bld = bld.initialCapacity(config.getPlaceCacheInitialCapacity());
   }

   if (config.getPlaceCacheMaxSize() > 0) {
      bld = bld.maximumSize(config.getPlaceCacheMaxSize());
   }

   if (config.isPlaceCacheSoftValues()) {
      bld = bld.softValues();
   }

   this.executors = bld
      .recordStats()
      .<UUID, SubsystemExecutor>removalListener((event) -> onRemoved(event.getValue()))
      .build();

   IrisMetricSet metrics = IrisMetrics.metrics("subsystems");
   metrics.monitor("cache", executors);
}