org.ehcache.Cache类的使用及代码示例

x33g5p2x  于2022-01-18 转载在 其他  
字(10.4k)|赞(0)|评价(0)|浏览(227)

本文整理了Java中org.ehcache.Cache类的一些代码示例,展示了Cache类的具体用法。这些代码示例主要来源于Github/Stackoverflow/Maven等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Cache类的具体详情如下:
包路径:org.ehcache.Cache
类名称:Cache

Cache介绍

[英]Defines all operational methods to create, access, update and delete mappings of key to value.

In order to function, cache keys must respect the Object#hashCode() and Object#equals(Object) contracts. This contract is what will be used to lookup values based on key.

A Cache is not a map, mostly because it has the following two concepts linked to mappings:

  • Eviction: A Cache has a capacity constraint and in order to honor it, a Cache can evict (remove) a mapping at any point in time. Note that eviction may occur before maximum capacity is reached.
  • Expiry: Data in a Cache can be configured to expire after some time. There is no way for a Cache user to differentiate from the API between a mapping being absent or expired.
    [中]定义创建、访问、更新和删除键到值映射的所有操作方法。
    为了发挥作用,缓存键必须遵守对象#hashCode()和对象#equals(对象)契约。此契约将用于根据键查找值。
    缓存不是映射,主要是因为它有以下两个链接到映射的概念:
    *逐出:缓存有容量限制,为了满足这一限制,缓存可以在任何时间点逐出(删除)映射。请注意,驱逐可能在达到最大容量之前发生。
    *过期:缓存中的数据可以配置为在一段时间后过期。缓存用户无法从API中区分映射缺失或过期。

代码示例

代码示例来源:origin: ehcache/ehcache3

private void put(Cache<Long, String> cache, String value, boolean addToCacheRecords) {
 cache.put(KEY, value);
 if (addToCacheRecords) {
  cacheRecords.add(new Record(KEY, cache.get(KEY)));
 }
}

代码示例来源:origin: ehcache/ehcache3

@Test
@SuppressWarnings("unchecked")
public void testSimpleRemove2ArgsWithLoaderAndWriter_existsInStore_notEquals() throws Exception {
 testCache.put(1, "un");
 reset(cacheLoaderWriter);
 assertThat(testCache.remove(1, "one"), is(false));
 verifyZeroInteractions(cacheLoaderWriter);
}

代码示例来源:origin: ehcache/ehcache3

@Test
 public void testClusteredWriteBehindLoading() throws Exception {
  cache.put(KEY, "Some value");
  checkValueFromLoaderWriter(cache, "Some value");
  cache.clear();

  assertThat(cache.get(KEY), notNullValue());

  doThreadDump = false;
 }
}

代码示例来源:origin: ehcache/ehcache3

private void replace(Cache<Long, String> cache, String value, boolean addToCacheRecords) {
 cache.replace(KEY, value);
 if (addToCacheRecords) {
  cacheRecords.add(new Record(KEY, cache.get(KEY)));
 }
}

代码示例来源:origin: ehcache/ehcache3

private void putIfAbsent(Cache<Long, String> cache, String value, boolean addToCacheRecords) {
 cache.putIfAbsent(KEY, value);
 if (addToCacheRecords) {
  cacheRecords.add(new Record(KEY, cache.get(KEY)));
 }
}

代码示例来源:origin: ehcache/ehcache3

@Test
@SuppressWarnings("unchecked")
public void testSimplePutIfAbsentWithLoaderAndWriter_existsInStore() throws Exception {
 testCache.put(1, "un");
 reset(cacheLoaderWriter);
 assertThat(testCache.putIfAbsent(1, "one"), Matchers.<CharSequence>equalTo("un"));
 assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("un"));
 verifyZeroInteractions(cacheLoaderWriter);
}

代码示例来源:origin: ehcache/ehcache3

private void innerClear() {
 cache.get(1); // one miss
 cache.getAll(asSet(1, 2, 3)); // 3 misses
 cache.put(1, "a"); // one put
 cache.put(1, "b"); // one put and update
 cache.putAll(Collections.singletonMap(2, "b")); // 1 put
 cache.get(1); // one hit
 cache.remove(1); // one remove
 cache.removeAll(asSet(2)); // one remove
 changesOf(1, 4, 3, 2);
 tierStatistics.clear();
 changesOf(-1, -4, -3, -2);
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testSimpleRemove() throws Exception {
 Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache", newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(10)));
 testCache.put(1, "one");
 testCache.put(2, "two");
 testCache.remove(1);
 assertThat(testCache.get(1), is(nullValue()));
 assertThat(testCache.get(2), is(notNullValue()));
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testPutIfAbsentWithWriterException_should_call_writer() throws Exception {
 doThrow(new Exception("Mock Exception: cannot write 1")).when(cacheLoaderWriter).write(eq(1), eq("one"));
 try {
  testCache.putIfAbsent(1, "one");
  fail("expected CacheWritingException");
 } catch (CacheWritingException ex) {
  // expected
 }
 testCache.put(2, "two");
 testCache.putIfAbsent(2, "two#2");
}

代码示例来源:origin: ehcache/ehcache3

private void performActualTest(Cache<Long, String> testCache) {
 final List<Long> expiredKeys = new CopyOnWriteArrayList<>();
 testCache.getRuntimeConfiguration().registerCacheEventListener(event -> expiredKeys.add(event.getKey()), EventOrdering.ORDERED, EventFiring.SYNCHRONOUS, EnumSet.of(EventType.EXPIRED));
 testCache.put(1L, "one");
 testCache.put(2L, "two");
 testCache.put(3L, "three");
 testCache.put(4L, "four");
 testCache.put(5L, "five");
 testCache.put(6L, "six");
 testCache.put(7L, "seven");
 testCache.get(1L);
 testCache.get(2L);
 testCache.get(3L);
 testCache.get(4L);
 testCache.get(5L);
 testTimeSource.setTimeMillis(1100);
 testCache.get(1L);
 testCache.get(2L);
 testCache.get(3L);
 testCache.get(4L);
 testCache.get(5L);
 testCache.get(6L);
 testCache.get(7L);
 assertThat(expiredKeys, containsInAnyOrder(1L, 2L, 3L, 4L, 5L, 6L, 7L));
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testSimpleReplace3ArgsWithLoaderAndWriter_existsInSor_notEquals() throws Exception {
 when(cacheLoaderWriter.load(eq(1))).thenAnswer((Answer) invocation -> "un");
 assertThat(testCache.containsKey(1), is(false));
 assertThat(testCache.replace(1, "uno", "one"), is(false));
 assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("un"));
 verify(cacheLoaderWriter, times(1)).load(eq(1));
 verifyNoMoreInteractions(cacheLoaderWriter);
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testContainsKeyExpiredTwoClients() {
 TestTimeSource timeSource = new TestTimeSource();
 TimeSourceConfiguration timeSourceConfiguration = new TimeSourceConfiguration(timeSource);
 final CacheManagerBuilder<PersistentCacheManager> clusteredCacheManagerBuilder =
   commonClusteredCacheManagerBuilder.using(timeSourceConfiguration);
 final PersistentCacheManager cacheManager1 = clusteredCacheManagerBuilder.build(true);
 final PersistentCacheManager cacheManager2 = clusteredCacheManagerBuilder.build(true);
 final Cache<Long, String> cache1 = cacheManager1.getCache("clustered-cache", Long.class, String.class);
 final Cache<Long, String> cache2 = cacheManager2.getCache("clustered-cache", Long.class, String.class);
 assertThat(cache2.get(1L), nullValue());
 cache1.put(1L, "value1");
 assertThat(cache1.containsKey(1L), is(true));
 timeSource.advanceTime(1L);
 assertThat(cache1.containsKey(1L), is(false));
 assertThat(cache2.containsKey(1L), is(false));
 cacheManager2.close();
 cacheManager1.close();
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testSimplePutIfAbsentWithLoaderAndWriter_absent() throws Exception {
 assertThat(testCache.containsKey(1), is(false));
 assertThat(testCache.putIfAbsent(1, "one"), is(nullValue()));
 assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("one"));
 verify(cacheLoaderWriter, times(1)).load(eq(1));
 verify(cacheLoaderWriter, times(1)).write(eq(1), eq("one"));
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testSimpleContainsKey() throws Exception {
 Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache", newCacheConfigurationBuilder(Number.class, CharSequence.class, heap(10)));
 testCache.put(1, "one");
 assertThat(testCache.containsKey(1), is(true));
 assertThat(testCache.containsKey(2), is(false));
}

代码示例来源:origin: ehcache/ehcache3

@Test(timeout=180000)
public void testClear() throws Exception {
 List<Cache<Long, BlobValue>> caches = new ArrayList<>();
 caches.add(CACHE1);
 caches.add(CACHE2);
 Map<Long, BlobValue> entriesMap = new HashMap<>();
 Random random = new Random();
 LongStream longStream = random.longs(1000);
 longStream.forEach(x -> entriesMap.put(x, new BlobValue()));
 caches.forEach(cache -> cache.putAll(entriesMap));
 Set<Long> keySet = entriesMap.keySet();
 Set<Long> readKeysByCache2BeforeFailOver = new HashSet<>();
 keySet.forEach(x -> {
  if (CACHE2.get(x) != null) {
   readKeysByCache2BeforeFailOver.add(x);
  }
 });
 CACHE1.clear();
 CLUSTER.getClusterControl().terminateActive();
 if (cacheConsistency == Consistency.STRONG) {
  readKeysByCache2BeforeFailOver.forEach(x -> assertThat(CACHE2.get(x), nullValue()));
 } else {
  readKeysByCache2BeforeFailOver.forEach(x -> assertThat(CACHE1.get(x), nullValue()));
 }
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void registerListenerAtRuntime() {
 CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder()
   .withCache("cache", CacheConfigurationBuilder.newCacheConfigurationBuilder(Long.class, String.class,
     ResourcePoolsBuilder.heap(10L)))
   .build(true);
 Cache<Long, String> cache = cacheManager.getCache("cache", Long.class, String.class);
 // tag::registerListenerAtRuntime[]
 ListenerObject listener = new ListenerObject(); // <1>
 cache.getRuntimeConfiguration().registerCacheEventListener(listener, EventOrdering.ORDERED,
   EventFiring.ASYNCHRONOUS, EnumSet.of(EventType.CREATED, EventType.REMOVED)); // <2>
 cache.put(1L, "one");
 cache.put(2L, "two");
 cache.remove(1L);
 cache.remove(2L);
 cache.getRuntimeConfiguration().deregisterCacheEventListener(listener); // <3>
 cache.put(1L, "one again");
 cache.remove(1L);
 // end::registerListenerAtRuntime[]
 cacheManager.close();
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void clear() {
 cache.put(1, "a");
 cache.put(2, "b");
 changesOf(0, 0, 2, 0);
 cache.clear();
 changesOf(0, 0, 0, 0);
}

代码示例来源:origin: ehcache/ehcache3

@SuppressWarnings("unchecked")
@Exposed
public void put(@Named("key") Object key, @Named("value") Object value) {
 Object convertedKey = convert(key, cacheBinding.getCache().getRuntimeConfiguration().getKeyType());
 Object convertedValue = convert(value, cacheBinding.getCache().getRuntimeConfiguration().getValueType());
 cacheBinding.getCache().put(convertedKey, convertedValue);
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testSimplePutWithExpiry_remove2Args() throws Exception {
 insert(testCache, getEntries());
 assertThat(cacheSize(testCache), is(2));
 manualTimeSource.setTimeMillis(1001);
 assertThat(testCache.remove(1, "one"), is(false));
 assertThat(testCache.get(1), is(nullValue()));
 assertThat(testCache.remove(2, "two"), is(false));
 assertThat(testCache.get(2), is(nullValue()));
}

代码示例来源:origin: ehcache/ehcache3

@Test
public void testGetWithLoaderException() throws Exception {
 when(cacheLoaderWriter.load(eq(1))).thenThrow(new Exception("TestException: cannot load data"));
 try {
  testCache.get(1);
  fail("expected CacheLoadingException");
 } catch (CacheLoadingException ex) {
  // expected
 }
 verify(cacheLoaderWriter, times(1)).load(eq(1));
}

相关文章