第 11 章 JCache (JSR-107) API


Data Grid 提供 JCache 1.0 API 的实现(js -107 )。JCACHE 指定用于在内存中缓存临时 Java 对象的标准 Java API。缓存 java 对象有助于瓶颈源自使用比较昂贵的数据(例如 DB 或 Web 服务),或难以计算的数据。在内存中缓存这些对象有助于直接从内存检索数据,而不必进行昂贵的往返或重新计算。本文档论述了如何将 JCache 与规范的 Data Grid 实现一起使用,并解释了 API 的关键方面。

11.1. 创建嵌入式缓存

先决条件

  1. 确保 cache-api 位于您的 classpath 上。
  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. 配置嵌入式缓存

  • 将自定义 Data Grid 配置的 URI 传递给 cache 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,因此缓存外的对象的状态变异不会对存储在缓存中的对象产生影响。数据科学家目前使用序列化/合并来制作存储在缓存中的副本,并遵循 spec。因此,如果在 Data Grid 中使用默认 JCache 配置,则存储的数据必须是 marshallable。

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

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

学习

尝试、购买和销售

社区

关于红帽文档

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

让开源更具包容性

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

關於紅帽

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

© 2024 Red Hat, Inc.