第 14 章 JCache (JSR-107) API


Data Grid 提供 JCache 1.0 API 的实施( JSR-107 )。JCACHE 指定用于在内存中缓存临时 Java 对象的标准 Java API。缓存 java 对象有助于防止使用代价昂贵的数据(例如,DB 或 Web 服务)或难以计算的数据造成瓶颈。在内存中缓存这些类型的对象有助于加快应用性能,方法是直接从内存检索数据,而不是执行昂贵的往返或重新计算。本文档论述了如何在规范的 Data Grid 实现中使用 JCache,并解释了 API 的关键方面。

14.1. 创建嵌入式缓存

先决条件

  1. 确保您的 cache-api 位于您的 classpath 上。
  2. 将以下依赖项添加到 pom.xml 中:

    <dependency>
      <groupId>org.infinispan</groupId>
      <artifactId>infinispan-jcache</artifactId>
    </dependency>
    Copy to Clipboard Toggle word wrap

流程

  • 创建使用默认 JCache API 配置的嵌入式缓存,如下所示:
import javax.cache.*;
import javax.cache.configuration.*;

// Retrieve the system wide cache manager
CacheManager cacheManager = Caching.getCachingProvider().getCacheManager();
// Define a named cache with default JCache configuration
Cache<String, String> cache = cacheManager.createCache("namedCache",
      new MutableConfiguration<String, String>());
Copy to Clipboard Toggle word wrap

14.1.1. 配置嵌入式缓存

  • 将自定义 Data Grid 配置的 URI 传递给 caching Provider.getCacheManager (URI) 调用,如下所示:
import java.net.URI;
import javax.cache.*;
import javax.cache.configuration.*;

// Load configuration from an absolute filesystem path
URI uri = URI.create("file:///path/to/infinispan.xml");
// Load configuration from a classpath resource
// URI uri = this.getClass().getClassLoader().getResource("infinispan.xml").toURI();

// Create a cache manager using the above configuration
CacheManager cacheManager = Caching.getCachingProvider().getCacheManager(uri, this.getClass().getClassLoader(), null);
Copy to Clipboard Toggle word wrap
警告

默认情况下,JCache API 指定数据应存储为 storeByValue,因此,操作之外的对象状态不会对缓存中存储的对象产生影响。目前,数据网格使用 serialization/marshalling 来实现此目的,从而使副本存储在缓存中,并遵循 spec。因此,如果将默认 JCache 配置与 Data Grid 一起使用,则存储的数据必须可以被处理。

另外,也可以通过参考(如 Data Grid 或 JDK Collections 工作)将 JCache 配置为存储数据。要做到这一点,只需调用:

Cache<String, String> cache = cacheManager.createCache("namedCache",
      new MutableConfiguration<String, String>().setStoreByValue(false));
Copy to Clipboard Toggle word wrap
返回顶部
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

通过我们的产品和服务,以及可以信赖的内容,帮助红帽用户创新并实现他们的目标。 了解我们当前的更新.

让开源更具包容性

红帽致力于替换我们的代码、文档和 Web 属性中存在问题的语言。欲了解更多详情,请参阅红帽博客.

關於紅帽

我们提供强化的解决方案,使企业能够更轻松地跨平台和环境(从核心数据中心到网络边缘)工作。

Theme

© 2025 Red Hat