com.github.benmanes.caffeine.cache.CacheLoader Java Examples

The following examples show how to use com.github.benmanes.caffeine.cache.CacheLoader. 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: CaffeineCacheManagerTests.java    From spring-analysis-note with MIT License 6 votes vote down vote up
@Test
public void cacheLoaderUseLoadingCache() {
	CaffeineCacheManager cm = new CaffeineCacheManager("c1");
	cm.setCacheLoader(new CacheLoader<Object, Object>() {
		@Override
		public Object load(Object key) throws Exception {
			if ("ping".equals(key)) {
				return "pong";
			}
			throw new IllegalArgumentException("I only know ping");
		}
	});
	Cache cache1 = cm.getCache("c1");
	Cache.ValueWrapper value = cache1.get("ping");
	assertNotNull(value);
	assertEquals("pong", value.get());

	assertThatIllegalArgumentException().isThrownBy(() ->
			assertNull(cache1.get("foo")))
		.withMessageContaining("I only know ping");
}
 
Example #2
Source File: CacheTest.java    From zuihou-admin-boot with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    LoadingCache<String, Map<String, Object>> caches = Caffeine.newBuilder()
            .maximumSize(10)
            .refreshAfterWrite(10000, TimeUnit.MINUTES)
            .build(new CacheLoader<String, Map<String, Object>>() {
                       @Nullable
                       @Override
                       public Map<String, Object> load(@NonNull String s) throws Exception {

                           Map<String, Object> map = new HashMap<>();
                           map.put("aaa", "aaa");
                           return map;
                       }
                   }
            );


    Map<String, Object> aaa = caches.get("aaa");
    System.out.println(aaa);
    Map<String, Object> bbb = caches.get("aaa");
    System.out.println(bbb);
    Map<String, Object> bbb1 = caches.get("aaa1");
    System.out.println(bbb1);

}
 
Example #3
Source File: CaffeineCacheManagerTests.java    From java-technology-stack with MIT License 6 votes vote down vote up
@Test
public void cacheLoaderUseLoadingCache() {
	CaffeineCacheManager cm = new CaffeineCacheManager("c1");
	cm.setCacheLoader(new CacheLoader<Object, Object>() {
		@Override
		public Object load(Object key) throws Exception {
			if ("ping".equals(key)) {
				return "pong";
			}
			throw new IllegalArgumentException("I only know ping");
		}
	});
	Cache cache1 = cm.getCache("c1");
	Cache.ValueWrapper value = cache1.get("ping");
	assertNotNull(value);
	assertEquals("pong", value.get());

	thrown.expect(IllegalArgumentException.class);
	thrown.expectMessage("I only know ping");
	assertNull(cache1.get("foo"));
}
 
Example #4
Source File: CacheTest.java    From zuihou-admin-cloud with Apache License 2.0 6 votes vote down vote up
@Test
public void test() {
    LoadingCache<String, Map<String, Object>> caches = Caffeine.newBuilder()
            .maximumSize(10)
            .refreshAfterWrite(10000, TimeUnit.MINUTES)
            .build(new CacheLoader<String, Map<String, Object>>() {
                       @Nullable
                       @Override
                       public Map<String, Object> load(@NonNull String s) throws Exception {

                           Map<String, Object> map = new HashMap<>();
                           map.put("aaa", "aaa");
                           return map;
                       }
                   }
            );


    Map<String, Object> aaa = caches.get("aaa");
    System.out.println(aaa);
    Map<String, Object> bbb = caches.get("aaa");
    System.out.println(bbb);
    Map<String, Object> bbb1 = caches.get("aaa1");
    System.out.println(bbb1);

}
 
Example #5
Source File: CaffeineCacheManagerTests.java    From spring-analysis-note with MIT License 5 votes vote down vote up
@Test
public void changeCacheLoaderRecreateCache() {
	CaffeineCacheManager cm = new CaffeineCacheManager("c1");
	Cache cache1 = cm.getCache("c1");

	CacheLoader<Object, Object> loader = mockCacheLoader();
	cm.setCacheLoader(loader);
	Cache cache1x = cm.getCache("c1");
	assertTrue(cache1x != cache1);

	cm.setCacheLoader(loader); // Set same instance
	Cache cache1xx = cm.getCache("c1");
	assertSame(cache1x, cache1xx);
}
 
Example #6
Source File: CaffeineLoadCacheIntegrationTest.java    From wildfly-camel with Apache License 2.0 5 votes vote down vote up
@Before
public void before() throws Exception {
    CacheLoader<Integer, Integer> cl = new CacheLoader<Integer, Integer>() {
        public Integer load(Integer key) throws Exception {
            return key + 1;
        }
    };
    cache = Caffeine.newBuilder().build(cl);

    camelctx = new WildFlyCamelContext();
    Context jndi = camelctx.getNamingContext();
    jndi.rebind("cache", cache);
}
 
Example #7
Source File: CaffeineCacheFactory.java    From cache2k-benchmark with Apache License 2.0 5 votes vote down vote up
@Override
public <K, V> BenchmarkCache<K, V> createUnspecializedLoadingCache(
  final Class<K> _keyType, final Class<V> _valueType,
  final int _maxElements, final BenchmarkCacheLoader<K, V> _source) {
  CacheLoader<K,V> l = new CacheLoader<K, V>() {
    @Override
    public V load(final K key) {
      return _source.load(key);
    }
  };
  MyLoadingBenchmarkCache c = new MyLoadingBenchmarkCache();
  c.cache = createCache(_maxElements).build(l);
  return c;
}
 
Example #8
Source File: CacheMetricsCollectorTest.java    From client_java with Apache License 2.0 5 votes vote down vote up
@SuppressWarnings("unchecked")
@Test
public void loadingCacheExposesMetricsForLoadsAndExceptions() throws Exception {
    CacheLoader<String, String> loader = mock(CacheLoader.class);
    when(loader.load(anyString()))
            .thenReturn("First User")
            .thenThrow(new RuntimeException("Seconds time fails"))
            .thenReturn("Third User");

    LoadingCache<String, String> cache = Caffeine.newBuilder().recordStats().build(loader);
    CollectorRegistry registry = new CollectorRegistry();
    CacheMetricsCollector collector = new CacheMetricsCollector().register(registry);
    collector.addCache("loadingusers", cache);

    cache.get("user1");
    cache.get("user1");
    try {
        cache.get("user2");
    } catch (Exception e) {
        // ignoring.
    }
    cache.get("user3");

    assertMetric(registry, "caffeine_cache_hit_total", "loadingusers", 1.0);
    assertMetric(registry, "caffeine_cache_miss_total", "loadingusers", 3.0);

    assertMetric(registry, "caffeine_cache_load_failure_total", "loadingusers", 1.0);
    assertMetric(registry, "caffeine_cache_loads_total", "loadingusers", 3.0);

    assertMetric(registry, "caffeine_cache_load_duration_seconds_count", "loadingusers", 3.0);
    assertMetricGreatThan(registry, "caffeine_cache_load_duration_seconds_sum", "loadingusers", 0.0);
}
 
Example #9
Source File: CacheContext.java    From caffeine with Apache License 2.0 5 votes vote down vote up
public <K, V> LoadingCache<K, V> build(CacheLoader<K, V> loader) {
  LoadingCache<K, V> cache;
  if (isCaffeine()) {
    cache = isAsync() ? caffeine.buildAsync(loader).synchronous() : caffeine.build(loader);
  } else {
    cache = new GuavaLoadingCache<>(guava.build(
        com.google.common.cache.CacheLoader.asyncReloading(
            new SingleLoader<>(loader), executor)), ticker, isRecordingStats());
  }
  this.cache = cache;
  return cache;
}
 
Example #10
Source File: BaseStellarProcessor.java    From metron with Apache License 2.0 5 votes vote down vote up
static Cache<String, StellarCompiler.Expression> createCache( int cacheSize
                                                     , int expiryTime
                                                     , TimeUnit expiryUnit
                                                     ) {
  CacheLoader<String, StellarCompiler.Expression> loader = key -> compile(key);
  return Caffeine.newBuilder()
                 .maximumSize(cacheSize)
                 .expireAfterAccess(expiryTime, expiryUnit)
                 .build(loader);
}
 
Example #11
Source File: CaffeineCacheManagerTests.java    From java-technology-stack with MIT License 5 votes vote down vote up
@Test
public void changeCacheLoaderRecreateCache() {
	CaffeineCacheManager cm = new CaffeineCacheManager("c1");
	Cache cache1 = cm.getCache("c1");

	CacheLoader<Object, Object> loader = mockCacheLoader();
	cm.setCacheLoader(loader);
	Cache cache1x = cm.getCache("c1");
	assertTrue(cache1x != cache1);

	cm.setCacheLoader(loader); // Set same instance
	Cache cache1xx = cm.getCache("c1");
	assertSame(cache1x, cache1xx);
}
 
Example #12
Source File: CaffeineUtils.java    From t-io with Apache License 2.0 4 votes vote down vote up
/**
 * @param cacheName
 * @param timeToLiveSeconds 设置写缓存后过期时间(单位:秒)
 * @param timeToIdleSeconds 设置读缓存后过期时间(单位:秒)
 * @param initialCapacity
 * @param maximumSize
 * @param recordStats
 * @param removalListener
 * @return
 */
public static <K, V> LoadingCache<K, V> createLoadingCache(String cacheName, Long timeToLiveSeconds, Long timeToIdleSeconds, Integer initialCapacity, Integer maximumSize,
        boolean recordStats, RemovalListener<K, V> removalListener) {

	if (removalListener == null) {
		removalListener = new DefaultRemovalListener<K, V>(cacheName);
	}

	Caffeine<K, V> cacheBuilder = Caffeine.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 #13
Source File: CaffeineCacheManagerTests.java    From java-technology-stack with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private CacheLoader<Object, Object> mockCacheLoader() {
	return mock(CacheLoader.class);
}
 
Example #14
Source File: CaffeinatedGuavaLoadingCache.java    From caffeine with Apache License 2.0 4 votes vote down vote up
SingleLoader(com.google.common.cache.CacheLoader<K, V> cacheLoader) {
  this.cacheLoader = requireNonNull(cacheLoader);
}
 
Example #15
Source File: CaffeinatedGuavaLoadingCache.java    From caffeine with Apache License 2.0 4 votes vote down vote up
BulkLoader(com.google.common.cache.CacheLoader<K, V> cacheLoader) {
  super(cacheLoader);
}
 
Example #16
Source File: CacheContext.java    From caffeine with Apache License 2.0 4 votes vote down vote up
public <K, V> AsyncLoadingCache<K, V> buildAsync(CacheLoader<K, V> loader) {
  checkState(isCaffeine() && isAsync());
  AsyncLoadingCache<K, V> cache = caffeine.buildAsync(loader);
  this.cache = cache.synchronous();
  return cache;
}
 
Example #17
Source File: CaffeineCacheManagerTests.java    From spring-analysis-note with MIT License 4 votes vote down vote up
@SuppressWarnings("unchecked")
private CacheLoader<Object, Object> mockCacheLoader() {
	return mock(CacheLoader.class);
}
 
Example #18
Source File: CaffeineCacheManager.java    From lams with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Set the Caffeine CacheLoader to use for building each individual
 * {@link CaffeineCache} instance, turning it into a LoadingCache.
 * @see #createNativeCaffeineCache
 * @see com.github.benmanes.caffeine.cache.Caffeine#build(CacheLoader)
 * @see com.github.benmanes.caffeine.cache.LoadingCache
 */
public void setCacheLoader(CacheLoader<Object, Object> cacheLoader) {
	if (!ObjectUtils.nullSafeEquals(this.cacheLoader, cacheLoader)) {
		this.cacheLoader = cacheLoader;
		refreshKnownCaches();
	}
}
 
Example #19
Source File: CaffeineCacheManager.java    From java-technology-stack with MIT License 3 votes vote down vote up
/**
 * Set the Caffeine CacheLoader to use for building each individual
 * {@link CaffeineCache} instance, turning it into a LoadingCache.
 * @see #createNativeCaffeineCache
 * @see com.github.benmanes.caffeine.cache.Caffeine#build(CacheLoader)
 * @see com.github.benmanes.caffeine.cache.LoadingCache
 */
public void setCacheLoader(CacheLoader<Object, Object> cacheLoader) {
	if (!ObjectUtils.nullSafeEquals(this.cacheLoader, cacheLoader)) {
		this.cacheLoader = cacheLoader;
		refreshKnownCaches();
	}
}
 
Example #20
Source File: CaffeineCacheManager.java    From spring-analysis-note with MIT License 3 votes vote down vote up
/**
 * Set the Caffeine CacheLoader to use for building each individual
 * {@link CaffeineCache} instance, turning it into a LoadingCache.
 * @see #createNativeCaffeineCache
 * @see com.github.benmanes.caffeine.cache.Caffeine#build(CacheLoader)
 * @see com.github.benmanes.caffeine.cache.LoadingCache
 */
public void setCacheLoader(CacheLoader<Object, Object> cacheLoader) {
	if (!ObjectUtils.nullSafeEquals(this.cacheLoader, cacheLoader)) {
		this.cacheLoader = cacheLoader;
		refreshKnownCaches();
	}
}