javax.cache.Caching类的使用及代码示例

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

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

Caching介绍

[英]The Caching class provides a convenient means for an application to acquire an appropriate CachingProvider implementation.

While defined as part of the specification, its use is not required. Applications and/or containers may instead choose to directly instantiate a CachingProvider implementation based on implementation specific instructions.

When using the Caching class, CachingProvider implementations are automatically discovered when they follow the conventions outlined by the Java Development Kit ServiceLoader class.

Although automatically discovered, applications that choose to use this class should not make assumptions regarding the order in which implementations are returned by the #getCachingProviders() or #getCachingProviders(ClassLoader) methods.

For a CachingProvider to be automatically discoverable by the Caching class, the fully qualified class name of the CachingProvider implementation must be declared in the following file:

META-INF/services/javax.cache.spi.CachingProvider

This file must be resolvable via the class path.

For example, in the reference implementation the contents of this file are: org.jsr107.ri.RICachingProvider

Alternatively when the fully qualified class name of a CachingProvider implementation is specified using the system property javax.cache.spi.cachingprovider, that implementation will be used as the default CachingProvider.

All CachingProviders that are automatically detected or explicitly declared and loaded by the Caching class are maintained in an internal registry. Consequently when a previously loaded CachingProvider is requested, it will be simply returned from the internal registry, without reloading and/or instantiating the said implementation again.

As required by some applications and containers, multiple co-existing CachingProviders implementations, from the same or different implementors are permitted at runtime.

To iterate through those that are currently registered a developer may use the following methods:

  1. #getCachingProviders()
  2. #getCachingProviders(ClassLoader)
    To request a specific CachingProvider implementation, a developer should use either the #getCachingProvider(String) or #getCachingProvider(String,ClassLoader) method.

Where multiple CachingProviders are present, the CachingProvider returned by getters #getCachingProvider() and #getCachingProvider(ClassLoader) is undefined and as a result a CacheException will be thrown when attempted.
[中]缓存类为应用程序获取适当的CachingProvider实现提供了方便的方法。
虽然定义为规范的一部分,但不需要使用。应用程序和/或容器可以选择根据特定于实现的指令直接实例化CachingProvider实现。
使用缓存类时,当CachingProvider实现遵循Java开发工具包ServiceLoader类概述的约定时,会自动发现它们。
尽管会自动发现,但选择使用此类的应用程序不应假设#getCachingProviders()或#getCachingProviders(ClassLoader)方法返回实现的顺序。
要使Caching类能够自动发现CachingProvider,必须在以下文件中声明CachingProvider实现的完全限定类名:

META-INF/services/javax.cache.spi.CachingProvider

此文件必须可通过类路径解析。
例如,在引用实现中,此文件的内容为:org.jsr107.ri.RICachingProvider
或者,当使用系统属性javax.cache.spi.cachingprovider指定CachingProvider实现的完全限定类名时,该实现将用作默认的CachingProvider。
由缓存类自动检测或显式声明并加载的所有cachingprovider都在内部注册表中维护。因此,当请求先前加载的CachingProvider时,它将仅从内部注册表返回,而无需再次重新加载和/或实例化所述实现。
根据某些应用程序和容器的要求,在运行时允许来自相同或不同实现者的多个共存CachingProviders实现。
要遍历当前注册的内容,开发人员可以使用以下方法:
1.#getCachingProviders()
1.#getCachingProviders(类加载器)
要请求特定的CachingProvider实现,开发人员应该使用#getCachingProvider(String)或#getCachingProvider(String,ClassLoader)方法。
如果存在多个CachingProvider,则getter#getCachingProvider()和#getCachingProvider(ClassLoader)返回的CachingProvider未定义,因此在尝试时将引发CacheException。

代码示例

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

@Test
public void testTypeOverriding() 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<>();
 cache1Conf.setTypes(Long.class, String.class);
 javax.cache.Cache<Long, String> cache = cacheManager.createCache("defaultCache", cache1Conf);
 @SuppressWarnings("unchecked")
 Configuration<Long, String> cache1CompleteConf = cache.getConfiguration(Configuration.class);
 assertThat(cache1CompleteConf.getKeyType(), is(equalTo(Long.class)));
 assertThat(cache1CompleteConf.getValueType(), is(equalTo(String.class)));
}

代码示例来源:origin: apache/incubator-dubbo

public JCache(URL url) {
  String method = url.getParameter(Constants.METHOD_KEY, "");
  String key = url.getAddress() + "." + url.getServiceKey() + "." + method;
  // jcache parameter is the full-qualified class name of SPI implementation
  String type = url.getParameter("jcache");
  CachingProvider provider = StringUtils.isEmpty(type) ? Caching.getCachingProvider() : Caching.getCachingProvider(type);
  CacheManager cacheManager = provider.getCacheManager();
  Cache<Object, Object> cache = cacheManager.getCache(key);
  if (cache == null) {
    try {
      //configure the cache
      MutableConfiguration config =
          new MutableConfiguration<Object, Object>()
              .setTypes(Object.class, Object.class)
              .setExpiryPolicyFactory(CreatedExpiryPolicy.factoryOf(new Duration(TimeUnit.MILLISECONDS, url.getMethodParameter(method, "cache.write.expire", 60 * 1000))))
              .setStoreByValue(false)
              .setManagementEnabled(true)
              .setStatisticsEnabled(true);
      cache = cacheManager.createCache(key, config);
    } catch (CacheException e) {
      // concurrent cache initialization
      cache = cacheManager.getCache(key);
    }
  }
  this.store = cache;
}

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

@Test
public void testRunTimeTypeLaxity() 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<>();
 cache1Conf.setTypes(Long.class, String.class);
 javax.cache.Cache<Long, String> cache = cacheManager.createCache("cache1", cache1Conf);
 @SuppressWarnings("unchecked")
 Configuration<Long, String> cache1CompleteConf = cache.getConfiguration(Configuration.class);
 assertThat(cache1CompleteConf.getKeyType(), is(equalTo(Long.class)));
 assertThat(cache1CompleteConf.getValueType(), is(equalTo(String.class)));
 try {
  cacheManager.getCache("cache1");
 } finally {
  cacheManager.destroyCache("cache1");
  cacheManager.close();
 }
}

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

@Test
 public void testCacheManagerCloseLenientToEhcacheClosed() 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);
  cacheManager.unwrap(org.ehcache.CacheManager.class).removeCache(cache.getName());
  cacheManager.close();
 }
}

代码示例来源:origin: redisson/redisson

Class<V> valueType) {
return getCachingProvider().getCacheManager().getCache(cacheName, keyType,
  valueType);

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

@Before
public void setUp() throws Exception {
 MockitoAnnotations.initMocks(this);
 CachingProvider provider = Caching.getCachingProvider();
 cacheManager = provider.getCacheManager(this.getClass().getResource("/ehcache-loader-writer-107-load-atomics.xml").toURI(), getClass().getClassLoader());
 testCache = cacheManager.createCache("testCache", new MutableConfiguration<Number, CharSequence>()
   .setReadThrough(true)
   .setWriteThrough(true)
   .setCacheLoaderFactory(() -> cacheLoader)
   .setCacheWriterFactory(() -> cacheWriter)
   .setTypes(Number.class, CharSequence.class));
}

代码示例来源:origin: org.wso2.carbon.identity/org.wso2.carbon.identity.mgt

protected Cache<String, UserIdentityClaimsDO> getCache() {
  CacheManager manager = Caching.getCacheManagerFactory().getCacheManager(InMemoryIdentityDataStore.IDENTITY_LOGIN_DATA_CACHE_MANAGER);
  Cache<String, UserIdentityClaimsDO> cache = manager.getCache(InMemoryIdentityDataStore.IDENTITY_LOGIN_DATA_CACHE);
  return cache;
}

代码示例来源:origin: ben-manes/caffeine

JCacheProfiler() {
 random = new Random();
 count = new LongAdder();
 CachingProvider provider = Caching.getCachingProvider(CaffeineCachingProvider.class.getName());
 CacheManager cacheManager = provider.getCacheManager(
   provider.getDefaultURI(), provider.getDefaultClassLoader());
 cache = cacheManager.createCache("profiler", new MutableConfiguration<>());
 executor = Executors.newCachedThreadPool(new ThreadFactoryBuilder()
   .setPriority(Thread.MIN_PRIORITY).setDaemon(true).build());
}

代码示例来源:origin: ben-manes/caffeine

@BeforeClass
public void beforeClass() {
 final CachingProvider provider = Caching.getCachingProvider(PROVIDER_NAME);
 cacheManager = provider.getCacheManager();
 cacheManager.destroyCache("cache-not-in-config-file");
 cacheConfig = new MutableConfiguration<>();
 cacheConfig.setTypes(String.class, String.class);
 cacheConfig.setStatisticsEnabled(true);
}

代码示例来源:origin: org.wso2.carbon.appmgt/org.wso2.carbon.appmgt.gateway

/**
 * get the cache manager
 * @return
 */
private static Cache getAppContextVersionConfigCache() {
  return Caching.getCacheManager(AppMConstants.APP_CONTEXT_VERSION_CACHE_MANAGER)
      .getCache(AppMConstants.APP_CONTEXT_VERSION_CONFIG_CACHE);
}

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

@Test
public void testLoaderConfiguration() throws Exception {
 final AtomicBoolean loaderCreated = new AtomicBoolean(false);
 MutableConfiguration<String, String> configuration = new MutableConfiguration<>();
 configuration.setTypes(String.class, String.class).setReadThrough(true);
 configuration.setCacheLoaderFactory(() -> {
  loaderCreated.set(true);
  return new TestCacheLoader();
 });
 CachingProvider provider = Caching.getCachingProvider();
 CacheManager cacheManager = provider.getCacheManager();
 Cache<String, String> cache = cacheManager.createCache("cache", configuration);
 assertThat(loaderCreated.get(), is(true));
 cache.putIfAbsent("42", "The Answer");
 TestCacheLoader.seen.clear();
 CompletionListenerFuture future = new CompletionListenerFuture();
 cache.loadAll(Collections.singleton("42"), true, future);
 future.get();
 assertThat(TestCacheLoader.seen, contains("42"));
}

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

@Test
public void testIterateExpiredReturnsNull() throws Exception {
 EhcacheCachingProvider provider = (EhcacheCachingProvider) Caching.getCachingProvider();
 TestTimeSource testTimeSource = new TestTimeSource();
 TimeSourceConfiguration timeSourceConfiguration = new TimeSourceConfiguration(testTimeSource);
 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));
 cacheManager.close();

代码示例来源:origin: spring-projects/spring-framework

@Override
public void afterPropertiesSet() {
  this.cacheManager = Caching.getCachingProvider().getCacheManager(
      this.cacheManagerUri, this.beanClassLoader, this.cacheManagerProperties);
}

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

@Test
public void testXAWorksWithJsr107() throws Exception {
 BitronixTransactionManager transactionManager = TransactionManagerServices.getTransactionManager();
 URI uri = getClass().getResource("/configs/simple-xa.xml").toURI();
 CacheManager cacheManager = Caching.getCachingProvider().getCacheManager(uri, getClass().getClassLoader());
 Cache<String, String> xaCache = cacheManager.getCache("xaCache", String.class, String.class);
 transactionManager.begin();
 {
   xaCache.put("key", "one");
 }
 transactionManager.commit();
 cacheManager.close();
}

代码示例来源:origin: zhangkaitao/spring4-1-showcase

@Bean
@Override
public CacheManager cacheManager() {
  javax.cache.CacheManager cacheManager = Caching.getCachingProvider().getCacheManager();
  MutableConfiguration<Object, Object> mutableConfiguration = new MutableConfiguration<Object, Object>();
  mutableConfiguration.setStoreByValue(false);  // otherwise value has to be Serializable
  cacheManager.createCache("user", mutableConfiguration);
  cacheManager.createCache("user2", mutableConfiguration);
  cacheManager.createCache("user3", mutableConfiguration);
  JCacheCacheManager jCacheCacheManager = new JCacheCacheManager(cacheManager);
  return jCacheCacheManager;
}

代码示例来源:origin: ben-manes/caffeine

@BeforeClass
public void beforeClass() {
 CachingProvider provider = Caching.getCachingProvider(PROVIDER_NAME);
 cacheManager = provider.getCacheManager(
   provider.getDefaultURI(), provider.getDefaultClassLoader());
}

代码示例来源:origin: com.github.bordertech.taskmaster/taskmaster-cache-helper

@Override
public synchronized <K, V> Cache<K, V> getOrCreateCache(final String name, final Class<K> keyClass,
    final Class<V> valueClass, final Configuration<K, V> config) {
  Cache<K, V> cache = Caching.getCache(name, keyClass, valueClass);
  if (cache == null) {
    final CacheManager mgr = Caching.getCachingProvider().getCacheManager();
    cache = mgr.createCache(name, config);
  }
  return cache;
}

代码示例来源:origin: apache/ignite

/**
 *
 */
@Test
public void testStartIgnite() {
  javax.cache.spi.CachingProvider cachingProvider = Caching.getCachingProvider();
  assert cachingProvider instanceof CachingProvider;
  CacheManager cacheMgr = cachingProvider.getCacheManager();
  assertEquals(Collections.<String>emptySet(), Sets.newHashSet(cacheMgr.getCacheNames()));
  Cache<Integer, String> cacheA = cacheMgr.createCache("a", new CacheConfiguration());
  cacheA.put(1, "1");
  assertEquals("1", cacheA.get(1));
  cacheMgr.createCache("b", new CacheConfiguration());
  assertEquals(Sets.newHashSet("a", "b"), Sets.newHashSet(cacheMgr.getCacheNames()));
  cacheMgr.destroyCache("a");
  cacheMgr.destroyCache("b");
  assertEquals(Collections.<String>emptySet(), Sets.newHashSet(cacheMgr.getCacheNames()));
}

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

@Test
public void testDefaultUriOverride() throws Exception {
 URI override = getClass().getResource("/ehcache-107.xml").toURI();
 Properties props = new Properties();
 props.put(DefaultConfigurationResolver.DEFAULT_CONFIG_PROPERTY_NAME, override);
 CacheManager cacheManager = Caching.getCachingProvider().getCacheManager(null, null, props);
 assertEquals(override, cacheManager.getURI());
 Caching.getCachingProvider().close();
}

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

@Before
public void setUp() throws Exception {
 cachingProvider = Caching.getCachingProvider();
 cacheManager = cachingProvider.getCacheManager(getClass().getResource("/ehcache-107-integration.xml")
   .toURI(), cachingProvider.getDefaultClassLoader());
}

相关文章