jcache 实现为ehcache 如何代码方式配置持久化的
时间: 2024-02-06 20:10:25 浏览: 224
ehcache-terracotta代码配置
5星 · 资源好评率100%
使用 Ehcache 作为 JCache 的实现,可以通过以下代码方式配置持久化:
```java
import javax.cache.CacheManager;
import javax.cache.Caching;
import javax.cache.configuration.MutableConfiguration;
import javax.cache.spi.CachingProvider;
import org.ehcache.config.builders.CacheConfigurationBuilder;
import org.ehcache.config.builders.ResourcePoolsBuilder;
import org.ehcache.config.units.EntryUnit;
import org.ehcache.config.units.MemoryUnit;
import org.ehcache.expiry.Duration;
import org.ehcache.expiry.Expirations;
import org.ehcache.jsr107.Eh107Configuration;
public class EhcacheJCachePersistenceExample {
public static void main(String[] args) {
// Create a cache manager using the CachingProvider for Ehcache
CachingProvider provider = Caching.getCachingProvider("org.ehcache.jsr107.EhcacheCachingProvider");
CacheManager cacheManager = provider.getCacheManager();
// Configure the cache
MutableConfiguration<Long, String> config = new MutableConfiguration<Long, String>()
.setTypes(Long.class, String.class)
.setExpiryPolicyFactory(Expirations.timeToLiveExpiration(Duration.ofSeconds(60)))
.setStoreByValue(false)
.setStatisticsEnabled(true)
.addCacheWriterFactory(new MyCacheWriterFactory());
// Add persistence configuration
CacheConfigurationBuilder<Long, String> cacheConfigurationBuilder = CacheConfigurationBuilder
.newCacheConfigurationBuilder(Long.class, String.class, ResourcePoolsBuilder.newResourcePoolsBuilder()
.heap(100, EntryUnit.ENTRIES)
.offheap(1, MemoryUnit.MB))
.withExpiry(Expirations.timeToLiveExpiration(Duration.ofSeconds(60)))
.withLoaderWriter(new MyCacheLoaderWriter())
.withService(new javax.cache.integration.CompositeCacheWriterConfiguration(new MyCacheWriterConfiguration()))
.withService(new javax.cache.integration.CompositeCacheLoaderWriterConfiguration(new MyCacheLoaderWriterConfiguration()))
.withService(new org.ehcache.jsr107.Eh107Configuration(Long.class, String.class, Expirations.timeToLiveExpiration(Duration.ofSeconds(60))))
.withDiskStore("persistent-cache");
// Create the cache
javax.cache.Cache<Long, String> cache = cacheManager.createCache("myCache", Eh107Configuration.fromEhcacheCacheConfiguration(cacheConfigurationBuilder.build()), config);
// Use the cache
cache.put(1L, "Hello, world!");
System.out.println(cache.get(1L));
// Close the cache manager and release resources
cacheManager.close();
provider.close();
}
}
```
其中,`withDiskStore("persistent-cache")` 配置了缓存持久化到磁盘的存储目录为 "persistent-cache"。同时,还可以通过 `withLoaderWriter()` 方法配置缓存的读写器,实现将数据持久化到磁盘或数据库中。
阅读全文