第 12 章 JCache (JSR-107) API
Data Grid 提供 JCache 1.0 API 的实施( JSR-107 )。JCACHE 指定用于在内存中缓存临时 Java 对象的标准 Java API。缓存 java 对象有助于防止使用代价昂贵的数据(例如,DB 或 Web 服务)或难以计算的数据造成瓶颈。在内存中缓存这些类型的对象有助于加快应用性能,方法是直接从内存检索数据,而不是执行昂贵的往返或重新计算。本文档论述了如何在规范的 Data Grid 实现中使用 JCache,并解释了 API 的关键方面。
12.1. 创建嵌入式缓存 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
先决条件
-
确保您的
cache-api位于您的 classpath 上。 将以下依赖项添加到
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>());
12.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);
警告
默认情况下,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));