com.google.common.cache.CacheBuilder#expireAfterAccess ( )源码实例Demo

下面列出了com.google.common.cache.CacheBuilder#expireAfterAccess ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

/**
 * 初始化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);
	}
}
 
源代码2 项目: localization_nifi   文件: TransformXml.java
@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");
    }
}
 
源代码3 项目: nifi   文件: TransformXml.java
@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");
    }
}
 
源代码4 项目: spring-cache-demo   文件: GuavaCacheFactoryBean.java
@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);
}
 
源代码5 项目: samza   文件: CachingTableProvider.java
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;
}
 
源代码6 项目: datacollector   文件: NetflowV9Decoder.java
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();
}
 
源代码7 项目: elasticsearch-dynarank   文件: DynamicRanker.java
@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();
}
 
源代码8 项目: phoenix   文件: TenantCacheImpl.java
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();
}
 
源代码9 项目: docker-plugin   文件: UsageTrackingCache.java
/**
 * 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();
}
 
源代码10 项目: Mybatis-PageHelper   文件: GuavaCache.java
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();
}
 
源代码11 项目: arcusplatform   文件: VoiceConfig.java
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;
}
 
@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);
}
 
源代码13 项目: alfresco-repository   文件: DefaultSimpleCache.java
/**
 * 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();
}
 
源代码14 项目: EVCache   文件: HotKeyListener.java
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;
    }
 
源代码15 项目: Elasticsearch   文件: IndicesRequestCache.java
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();
}
 
源代码16 项目: attic-apex-malhar   文件: CacheStore.java
@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);
}
 
源代码17 项目: arcusplatform   文件: CachingSubsystemRegistry.java
/**
 * 
 */
@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);
}
 
源代码18 项目: arcusplatform   文件: IrisSettings.java
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;
}
 
源代码19 项目: t-io   文件: GuavaUtils.java
/**
 *
 * @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());
}
 
源代码20 项目: Elasticsearch   文件: ScriptService.java
@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();
    }
}