本文整理了Java中javax.cache.Cache
类的一些代码示例,展示了Cache
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Cache
类的具体详情如下:
包路径:javax.cache.Cache
类名称:Cache
[英]A Cache is a Map-like data structure that provides temporary storage of application data.
Like Maps, Caches
Unlike Maps, Caches
null
will result in a NullPointerExceptionA simple example of how to use a cache is:
String cacheName = "sampleCache";
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
Cache<Integer, Date> cache = manager.getCache(cacheName, Integer.class,
Date.class);
Date value1 = new Date();
Integer key = 1;
cache.put(key, value1);
Date value2 = cache.get(key);
[中]缓存是一种类似于地图的数据结构,提供应用程序数据的临时存储。
像地图,缓存
1.存储键值对,每个键值对称为一个条目
1.允许使用Java泛型来提高应用程序类型安全性
1.你能忍受吗
与地图不同,缓存
1.不允许使用空键或值。尝试使用null
将导致NullPointerException
1.当请求的值不在缓存中时,提供从缓存加载程序读取值的能力(通过缓存读取)
1.提供在创建/更新/从缓存中删除值时将值写入CacheWriter(通过缓存写入)的功能
1.提供观察缓存项更改的能力
1.可以捕获和测量运营统计数据
如何使用缓存的一个简单示例是:
String cacheName = "sampleCache";
CachingProvider provider = Caching.getCachingProvider();
CacheManager manager = provider.getCacheManager();
Cache<Integer, Date> cache = manager.getCache(cacheName, Integer.class,
Date.class);
Date value1 = new Date();
Integer key = 1;
cache.put(key, value1);
Date value2 = cache.get(key);
代码示例来源:origin: apache/incubator-dubbo
@Override
public Object get(Object key) {
return store.get(key);
}
代码示例来源:origin: apache/incubator-dubbo
@Override
public void put(Object key, Object value) {
store.put(key, value);
}
代码示例来源:origin: spring-projects/spring-framework
@Override
public void evict(Object key) {
this.cache.remove(key);
}
代码示例来源:origin: requery/requery
@Override
public boolean contains(Class<?> type, Object key) {
Cache cache = getCache(type);
return cache != null && !cache.isClosed() && cache.containsKey(key);
}
代码示例来源:origin: requery/requery
@Override
public void invalidate(Class<?> type, Object key) {
Cache cache = getCache(type);
if (cache != null && !cache.isClosed()) {
cache.remove(key);
}
}
代码示例来源:origin: ben-manes/caffeine
/** Returns the object name of the management bean. */
private static ObjectName getObjectName(Cache<?, ?> cache, MBeanType type) {
String cacheManagerName = sanitize(cache.getCacheManager().getURI().toString());
String cacheName = sanitize(cache.getName());
try {
String name = String.format("javax.cache:type=Cache%s,CacheManager=%s,Cache=%s",
type, cacheManagerName, cacheName);
return new ObjectName(name);
} catch (MalformedObjectNameException e) {
String msg = String.format("Illegal ObjectName for cacheManager=[%s], cache=[%s]",
cacheManagerName, cacheName);
throw new CacheException(msg, e);
}
}
代码示例来源:origin: javax.cache/cache-tests
/**
* Ensure that {@link Cache#loadAll(java.util.Set, boolean, javax.cache.integration.CompletionListener)}
* won't load <code>null</code> entries.
*/
@Test
public void shouldNotLoadMultipleNullEntriesUsingLoadAll() throws Exception {
NullValueCacheLoader<String, String> cacheLoader = new NullValueCacheLoader<>();
cacheLoaderServer.setCacheLoader(cacheLoader);
HashSet<String> keys = new HashSet<>();
keys.add("gudday");
keys.add("hello");
keys.add("howdy");
keys.add("bonjour");
CompletionListenerFuture future = new CompletionListenerFuture();
cache.loadAll(keys, false, future);
//wait for the load to complete
future.get();
assertThat(future.isDone(), is(true));
for (String key : keys) {
assertThat(cache.containsKey(key), is(false));
}
}
代码示例来源:origin: apache/cxf
protected static <K, V extends ServerAccessToken> List<V> getTokens(Cache<K, V> cache,
Client client, UserSubject sub) {
final Set<K> toRemove = new HashSet<>();
final List<V> tokens = new ArrayList<>();
for (Iterator<Cache.Entry<K, V>> it = cache.iterator(); it.hasNext();) {
Cache.Entry<K, V> entry = it.next();
V token = entry.getValue();
if (isExpired(token)) {
toRemove.add(entry.getKey());
} else if (isTokenMatched(token, client, sub)) {
tokens.add(token);
}
}
cache.removeAll(toRemove);
return tokens;
}
代码示例来源:origin: javax.cache/cache-tests
/**
* Ensure that {@link Cache#loadAll(java.util.Set, boolean, javax.cache.integration.CompletionListener)}
* for a non-existent single value will cause it to be loaded.
*/
@Test
public void shouldLoadSingleMissingEntryUsingLoadAll() throws Exception {
RecordingCacheLoader<String> cacheLoader = new RecordingCacheLoader<String>();
cacheLoaderServer.setCacheLoader(cacheLoader);
String key = "message";
HashSet<String> keys = new HashSet<>();
keys.add(key);
assertThat(cache.containsKey(key), is(false));
CompletionListenerFuture future = new CompletionListenerFuture();
cache.loadAll(keys, false, future);
//wait for the load to complete
future.get();
assertThat(future.isDone(), is(true));
assertThat(cache.get(key), is(equalTo(key)));
assertThat(cacheLoader.getLoadCount(), is(1));
assertThat(cacheLoader.hasLoaded(key), is(true));
}
代码示例来源:origin: ehcache/ehcache3
@Test
public void test_getCacheHitsAndMisses() {
heapCache.put("key1", "value1");
heapCache.put("key3", "value3");
heapCache.put("key5", "value5");
HashSet<String> keys = new HashSet<>(5);
for (int i = 1; i <= 5; i++) {
keys.add("key" + i);
}
heapCache.getAll(keys);
assertThat(heapStatistics.getCacheHits(), is(3L));
assertThat(heapStatistics.getCacheMisses(), is(2L));
}
代码示例来源:origin: killbill/killbill
@Override
public void remove(final Function<K, Boolean> keyMatcher) {
final Set<K> toRemove = new HashSet<K>();
for (final Object key : getKeys()) {
if (keyMatcher.apply((K) key) == Boolean.TRUE) {
toRemove.add((K) key);
}
}
cache.removeAll(toRemove);
}
代码示例来源:origin: javax.cache/cache-tests
@Test
public void removeAll_1arg_NullKey() {
HashSet<Long> keys = new HashSet<Long>();
keys.add(null);
try {
cache.removeAll(keys);
fail("should have thrown an exception - null key not allowed");
} catch (NullPointerException e) {
//expected
}
}
代码示例来源:origin: javax.cache/cache-tests
@Test
public void getAllShouldCallGetExpiryForAccessedEntry() {
CountingExpiryPolicy expiryPolicy = new CountingExpiryPolicy();
expiryPolicyServer.setExpiryPolicy(expiryPolicy);
MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient));
Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config);
Set<Integer> keys = new HashSet<>();
keys.add(1);
keys.add(2);
// when getting a non-existent entry, getExpiryForAccessedEntry is not called.
cache.getAll(keys);
assertThat(expiryPolicy.getCreationCount(), is(0));
assertThat(expiryPolicy.getAccessCount(), is(0));
assertThat(expiryPolicy.getUpdatedCount(), is(0));
cache.put(1, 1);
cache.put(2, 2);
assertThat(expiryPolicy.getCreationCount(), greaterThanOrEqualTo(2));
assertThat(expiryPolicy.getAccessCount(), is(0));
assertThat(expiryPolicy.getUpdatedCount(), is(0));
expiryPolicy.resetCount();
// when getting an existing entry, getExpiryForAccessedEntry is called.
cache.get(1);
cache.get(2);
assertThat(expiryPolicy.getCreationCount(), is(0));
assertThat(expiryPolicy.getAccessCount(), greaterThanOrEqualTo(2));
assertThat(expiryPolicy.getUpdatedCount(), is(0));
expiryPolicy.resetCount();
}
代码示例来源:origin: javax.cache/cache-tests
@Test
public void iteratorNextShouldCallGetExpiryForAccessedEntry() {
CountingExpiryPolicy expiryPolicy = new CountingExpiryPolicy();
expiryPolicyServer.setExpiryPolicy(expiryPolicy);
MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient));
Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config);
Set<Integer> keys = new HashSet<>();
keys.add(1);
keys.add(2);
cache.put(1, 1);
cache.put(2, 2);
assertThat(expiryPolicy.getCreationCount(), greaterThanOrEqualTo(2));
assertThat(expiryPolicy.getAccessCount(), is(0));
assertThat(expiryPolicy.getUpdatedCount(), is(0));
expiryPolicy.resetCount();
// when getting an existing entry, getExpiryForAccessedEntry is called.
Iterator<Entry<Integer, Integer>> iter = cache.iterator();
int count = 0;
while (iter.hasNext()) {
Entry<Integer, Integer> entry = iter.next();
count++;
assertThat(expiryPolicy.getCreationCount(), is(0));
assertThat(expiryPolicy.getAccessCount(), greaterThanOrEqualTo(1));
assertThat(expiryPolicy.getUpdatedCount(), is(0));
expiryPolicy.resetCount();
}
}
代码示例来源:origin: ehcache/ehcache3
@SuppressWarnings("unchecked")
@Test
public void testXmlExampleIn107() throws Exception {
javax.cache.Cache<Long, Product> productCache = cacheManager.getCache("productCache", Long.class, Product.class);
assertThat(productCache, is(notNullValue()));
Configuration<Long, Product> configuration = productCache.getConfiguration(Configuration.class);
assertThat(configuration.getKeyType(), is(equalTo(Long.class)));
assertThat(configuration.getValueType(), is(equalTo(Product.class)));
Eh107ReverseConfiguration<Long, Product> eh107ReverseConfiguration = productCache.getConfiguration(Eh107ReverseConfiguration.class);
assertThat(eh107ReverseConfiguration.isReadThrough(), is(true));
assertThat(eh107ReverseConfiguration.isWriteThrough(), is(true));
assertThat(eh107ReverseConfiguration.isStoreByValue(), is(true));
Product product = new Product(1L);
productCache.put(1L, product);
assertThat(productCache.get(1L).getId(), equalTo(product.getId()));
product.setMutable("foo");
assertThat(productCache.get(1L).getMutable(), nullValue());
assertThat(productCache.get(1L), not(sameInstance(product)));
javax.cache.Cache<Long, Customer> customerCache = cacheManager.getCache("customerCache", Long.class, Customer.class);
assertThat(customerCache, is(notNullValue()));
Configuration<Long, Customer> customerConfiguration = customerCache.getConfiguration(Configuration.class);
assertThat(customerConfiguration.getKeyType(), is(equalTo(Long.class)));
assertThat(customerConfiguration.getValueType(), is(equalTo(Customer.class)));
Customer customer = new Customer(1L);
customerCache.put(1L, customer);
assertThat(customerCache.get(1L).getId(), equalTo(customer.getId()));
}
代码示例来源:origin: ehcache/ehcache3
@Test
@SuppressWarnings("unchecked")
public void testCompileTimeTypeSafety() throws Exception {
CachingProvider provider = Caching.getCachingProvider();
javax.cache.CacheManager cacheManager =
provider.getCacheManager(this.getClass().getResource("/ehcache-107-types.xml").toURI(), getClass().getClassLoader());
MutableConfiguration<Long, String> cache1Conf = new MutableConfiguration<>();
javax.cache.Cache<Long, String> cache = cacheManager.createCache("cache1", cache1Conf);
cache.put(1l, "one");
cache.put(2l, "two");
Configuration<Object, Object> cache1CompleteConf = cache.getConfiguration(Configuration.class);
//This ensures that we have compile time type safety, i.e when configuration does not have types defined but
// what you get cache as should work.
assertThat(cache1CompleteConf.getKeyType(), is(equalTo(Object.class)));
assertThat(cache1CompleteConf.getValueType(), is(equalTo(Object.class)));
assertThat(cache.get(1l), is(equalTo("one")));
assertThat(cache.get(2l), is(equalTo("two")));
javax.cache.Cache<String, String> second = cacheManager.getCache("cache1");
second.put("3","three");
assertThat(second.get("3"), is(equalTo("three")));
cacheManager.destroyCache("cache1");
cacheManager.close();
}
代码示例来源:origin: ehcache/ehcache3
@Test
public void testSimplePutIfAbsentWithLoaderAndWriter_existsInSor() throws Exception {
assertThat(testCache.containsKey(1), is(false));
assertThat(testCache.putIfAbsent(1, "one"), is(true));
assertThat(testCache.get(1), Matchers.<CharSequence>equalTo("one"));
verifyZeroInteractions(cacheLoader);
verify(cacheWriter, times(1)).write(eq(new Eh107CacheLoaderWriter.Entry<Number, CharSequence>(1, "one")));
}
代码示例来源:origin: javax.cache/cache-tests
@Test
public void containsKeyShouldNotCallExpiryPolicyMethods() {
CountingExpiryPolicy expiryPolicy = new CountingExpiryPolicy();
expiryPolicyServer.setExpiryPolicy(expiryPolicy);
MutableConfiguration<Integer, Integer> config = new MutableConfiguration<>();
config.setExpiryPolicyFactory(FactoryBuilder.factoryOf(expiryPolicyClient));
Cache<Integer, Integer> cache = getCacheManager().createCache(getTestCacheName(), config);
cache.containsKey(1);
assertThat(expiryPolicy.getCreationCount(), is(0));
assertThat(expiryPolicy.getAccessCount(), is(0));
assertThat(expiryPolicy.getUpdatedCount(), is(0));
cache.put(1, 1);
assertThat(expiryPolicy.getCreationCount(), greaterThanOrEqualTo(1));
assertThat(expiryPolicy.getAccessCount(), is(0));
assertThat(expiryPolicy.getUpdatedCount(), is(0));
expiryPolicy.resetCount();
cache.containsKey(1);
assertThat(expiryPolicy.getCreationCount(), is(0));
assertThat(expiryPolicy.getAccessCount(), is(0));
assertThat(expiryPolicy.getUpdatedCount(), is(0));
}
代码示例来源:origin: ehcache/ehcache3
@Test
public void test107LoaderOverriddenByEhcacheTemplateLoaderWriter() throws Exception {
final AtomicBoolean loaderFactoryInvoked = new AtomicBoolean(false);
final DumbCacheLoader product2CacheLoader = new DumbCacheLoader();
MutableConfiguration<Long, Product> product2Configuration = new MutableConfiguration<>();
product2Configuration.setTypes(Long.class, Product.class).setReadThrough(true);
product2Configuration.setCacheLoaderFactory(() -> {
loaderFactoryInvoked.set(true);
return product2CacheLoader;
});
Cache<Long, Product> productCache2 = cacheManager.createCache("productCache2", product2Configuration);
assertThat(loaderFactoryInvoked.get(), is(false));
Product product = productCache2.get(124L);
assertThat(product.getId(), is(124L));
assertThat(ProductCacheLoaderWriter.seen, hasItem(124L));
assertThat(product2CacheLoader.seen, is(empty()));
CompletionListenerFuture future = new CompletionListenerFuture();
productCache2.loadAll(Collections.singleton(42L), false, future);
future.get();
assertThat(ProductCacheLoaderWriter.seen, hasItem(42L));
assertThat(product2CacheLoader.seen, is(empty()));
}
代码示例来源:origin: ehcache/ehcache3
CacheManager cacheManager = provider.getCacheManager(new URI("test://testIterateExpiredReturnsNull"), new DefaultConfiguration(getClass().getClassLoader(), timeSourceConfiguration));
Cache<Number, CharSequence> testCache = cacheManager.createCache("testCache", new MutableConfiguration<Number, CharSequence>()
.setExpiryPolicyFactory(() -> new ExpiryPolicy() {
@Override
public Duration getExpiryForCreation() {
.setTypes(Number.class, CharSequence.class));
testCache.put(1, "one");
testCache.get(1);
Iterator<Cache.Entry<Number, CharSequence>> iterator = testCache.iterator();
assertThat(iterator.hasNext(), is(true));
assertThat(next, is(nullValue()));
assertThat(loopCount, is(1));
cacheManager.close();
内容来源于网络,如有侵权,请联系作者删除!