第 11 章 使用 JCache API


数据网格提供了 JCache (JSR-107) API 的实施,它指定了用于在内存中缓存临时 Java 对象的标准 Java API。缓存 Java 对象可以帮助使用数据出现瓶颈问题,因为无法检索或数据难以计算。在内存中缓存这些类型的对象有助于通过直接从内存检索数据来加快应用程序性能,而不是执行昂贵的往返或重新计算。

11.1. 创建嵌入缓存

先决条件

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

    <dependency>
      <groupId>org.infinispan</groupId>
      <artifactId>infinispan-jcache</artifactId>
    </dependency>

流程

  • 创建使用默认 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>());

11.1.1. 配置嵌入缓存

  • 将自定义数据网格配置的 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);
警告

默认情况下,JCache API 指定数据应存储为 storeByValue,因此对缓存的操作以外的对象状态变异,不会对缓存中存储的对象产生影响。到目前为止,使用 serialization/marshalling 进行了此实施,以便副本在缓存中存储,这种方式符合 spec。因此,如果将默认 JCache 配置用于 Data Grid,则存储的数据必须是一个摘要。

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

Cache<String, String> cache = cacheManager.createCache("namedCache",
      new MutableConfiguration<String, String>().setStoreByValue(false));
Red Hat logoGithubredditYoutubeTwitter

学习

尝试、购买和销售

社区

关于红帽文档

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

让开源更具包容性

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

關於紅帽

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

Theme

© 2026 Red Hat
返回顶部