4.3. 以编程方式配置缓存
使用 Cache Manager 定义缓存配置。
注意
本节中的示例使用 EmbeddedCacheManager,它是一个在与客户端相同的 JVM 中运行的 Cache Manager。
要使用 HotRod 客户端远程配置缓存,请使用 RemoteCacheManager。如需更多信息,请参阅 HotRod 文档。
配置新的缓存实例
以下示例配置一个新的缓存实例:
EmbeddedCacheManager manager = new DefaultCacheManager("infinispan-prod.xml");
Cache defaultCache = manager.getCache();
Configuration c = new ConfigurationBuilder().clustering()
.cacheMode(CacheMode.REPL_SYNC)
.build();
String newCacheName = "replicatedCache";
manager.defineConfiguration(newCacheName, c);
Cache<String, String> cache = manager.getCache(newCacheName);
从现有配置创建新缓存
以下示例从现有缓存配置创建新缓存配置:
EmbeddedCacheManager manager = new DefaultCacheManager("infinispan-prod.xml");
Configuration dcc = manager.getDefaultCacheConfiguration();
Configuration c = new ConfigurationBuilder().read(dcc)
.clustering()
.cacheMode(CacheMode.DIST_SYNC)
.l1()
.lifespan(60000L)
.build();
String newCacheName = "distributedWithL1";
manager.defineConfiguration(newCacheName, c);
Cache<String, String> cache = manager.getCache(newCacheName);
EmbeddedCacheManager manager = new DefaultCacheManager("infinispan-prod.xml");
Configuration rc = manager.getCacheConfiguration("replicatedCache");
Configuration c = new ConfigurationBuilder().read(rc)
.clustering()
.cacheMode(CacheMode.DIST_SYNC)
.l1()
.lifespan(60000L)
.build();
String newCacheName = "distributedWithL1";
manager.defineConfiguration(newCacheName, c);
Cache<String, String> cache = manager.getCache(newCacheName);
- 1
- 使用名为"replicatedCache"的缓存配置作为基础。