第 11 章 使用 JCache API
数据网格提供了 JCache (JSR-107) API 的实施,它指定了用于在内存中缓存临时 Java 对象的标准 Java API。缓存 Java 对象可以帮助使用数据出现瓶颈问题,因为无法检索或数据难以计算。在内存中缓存这些类型的对象有助于通过直接从内存检索数据来加快应用程序性能,而不是执行昂贵的往返或重新计算。
11.1. 创建嵌入缓存 复制链接链接已复制到粘贴板!
复制链接链接已复制到粘贴板!
先决条件
-
确保
cache-api位于您的类路径上。 将以下依赖项添加到
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));