Java EHcache是一个简单的例子,有生存时间
我需要一个简单的缓存,在内存中存储元组,并留有一定的生存时间。我在EHcache网站上找不到这样做的方法,该网站主要包含复杂的使用场景。有人能帮我吗 另外,我不使用Spring。Ehcache 2.x 纲领性 XML Ehcache 3.x 纲领性Java EHcache是一个简单的例子,有生存时间,java,caching,ehcache,Java,Caching,Ehcache,我需要一个简单的缓存,在内存中存储元组,并留有一定的生存时间。我在EHcache网站上找不到这样做的方法,该网站主要包含复杂的使用场景。有人能帮我吗 另外,我不使用Spring。Ehcache 2.x 纲领性 XML Ehcache 3.x 纲领性 生存时间与getExpiryForCreation调用相匹配,该调用将接收映射的键和值,允许根据映射本身实现不同的过期。对于EhCache版本3.3.1,groupId:org.EhCache,artifactId:EhCache,以下功能有效 Ca
生存时间与
getExpiryForCreation
调用相匹配,该调用将接收映射的键和值,允许根据映射本身实现不同的过期。对于EhCache版本3.3.1,groupId:org.EhCache,artifactId:EhCache
,以下功能有效
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("AllCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class,String.class,
ResourcePoolsBuilder.heap(100))
.withExpiry(Expirations.timeToLiveExpiration(new Duration(86400, TimeUnit.SECONDS)))
.build()).build(true);
Cache<String, String> allCache = cacheManager.getCache("AllCache", String.class, String.class);
CacheManager CacheManager=CacheManagerBuilder.newCacheManagerBuilder().withCache(“AllCache”,
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class、String.class、,
ResourcePoolsBuilder.heap(100))
.WithExpire(expirements.timeToLiveExpirement(新的持续时间(86400,时间单位.秒)))
.build()).build(true);
Cache allCache=cacheManager.getCache(“allCache”,String.class,String.class);
Ehcache 3.x解决方案,用于在运行时定义每个元素的到期日
此解决方案在Ehcache 3.8.1上测试为运行良好,但代码肯定对任何Ehcache 3.x都有效
首先创建一个类来保留一个泛型对象,实际上是可以传递给缓存的任何对象:
import java.io.Serializable;
import java.time.Duration;
public class EhcacheValue<T> implements Serializable {
private static final long serialVersionUID = 1L;
private T object;
private long timeToLive;
public EhcacheValue(T theObject, Duration theDuration) {
object = theObject;
timeToLive = theDuration.getSeconds();
}
public Duration getTimeToLiveDuration() {
return Duration.ofSeconds(timeToLive);
}
public T getObject() {
return object;
}
public void setObject(T theObject) {
object = theObject;
}
public long getTimeToLive() {
return timeToLive;
}
public void setTimeToLive(long theTimeToLive) {
timeToLive = theTimeToLive;
}
}
import java.io.Serializable;
导入java.time.Duration;
公共类EhcacheValue实现可序列化{
私有静态最终长serialVersionUID=1L;
私人T对象;
私人长期生活;
公共EhcacheValue(对象、持续时间){
对象=对象;
timeToLive=theDuration.getSeconds();
}
公共持续时间GetTimmeDuration(){
返回持续时间。秒(timeToLive);
}
公共T getObject(){
返回对象;
}
公共无效集合对象(T对象){
对象=对象;
}
公共长期服务{
返回时间间隔;
}
public void setTimeToLive(长时间){
timeToLive=三倍橄榄油;
}
}
然后创建一个自定义到期类,实现Ehcache 3.x接口ExpiryPolicy:
import java.time.Duration;
import java.util.function.Supplier;
import org.ehcache.expiry.ExpiryPolicy;
public class CustomExpiryPolicy<K, V extends EhcacheValue<?>> implements ExpiryPolicy<K, V> {
public CustomExpiryPolicy() {
}
@Override
public Duration getExpiryForCreation(K theKey, V theValue) {
return theValue.getTimeToLiveDuration();
}
@Override
public Duration getExpiryForAccess(K theKey, Supplier<? extends V> theValue) {
return null;
}
@Override
public Duration getExpiryForUpdate(K theKey, Supplier<? extends V> theOldValue, V theNewValue) {
return theNewValue.getTimeToLiveDuration();
}
}
public class TestEhCache {
private static final String CACHE_TIER_HEAP = "OnHeap";
public static void main(String[] args) {
StatisticsService statisticsService = new DefaultStatisticsService();
myCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.using(statisticsService)
.build();
//we init it here, not with boolean in build()
myCacheManager.init();
// Beware, the items are not expiring automatically, there are more mechanism in place for checking the expiration
// For instance the expiration is checked at get time
// for more details see the documentation from the version 2.8
// here: https://www.ehcache.org/documentation/2.8/apis/cache-event-listeners.html
// Unfortunately for the version 3.x doesn't exist a detailed depiction, but in main the procedure is the same
//
// Ehcache 2.8 documentation:
// Elements are checked for expiry in Ehcache at the following times:
//
// When a get request is made
// When an element is spooled to the diskStore in accordance with a MemoryStore eviction policy
// In the DiskStore when the expiry thread runs, which by default is
// net.sf.ehcache.Cache#DEFAULT_EXPIRY_THREAD_INTERVAL_SECONDS
CustomExpiryPolicy<String,EhcacheValue<?>> expiryPolicy = new CustomExpiryPolicy<String,EhcacheValue<?>>();
ResourcePools resourcePools = ResourcePoolsBuilder.newResourcePoolsBuilder().heap(2000L, EntryUnit.ENTRIES).build();
@SuppressWarnings("unchecked")
Class<EhcacheValue<?>> myEhcacheValue = (Class<EhcacheValue<?>>)(Class<?>)EhcacheValue.class;
CacheConfiguration<String,EhcacheValue<?>> cacheConfiguration = CacheConfigurationBuilder
.newCacheConfigurationBuilder(String.class, myEhcacheValue, resourcePools)
.withExpiry(expiryPolicy)
//.withService(new StoreStatisticsConfiguration(true)) // explicitly enable statistics, it seems is not needed
.build();
myCache = myCacheManager.createCache("myCache", cacheConfiguration);
myCacheStatistics = statisticsService.getCacheStatistics("myCache");
long cacheEntriesNr = myCacheStatistics.getTierStatistics().get(CACHE_TIER_HEAP).getMappings();
//nb element in heap tier
long sizeEntriesByStatistics = myCacheStatistics.getTierStatistics().get("OnHeap").getMappings();
//size of the tier in memory, when you set memory limits, not in this case
//long sizeBytesByStatistics = myCacheStatistics.getTierStatistics().get("OnHeap").getOccupiedByteSize();
long getsCnt = myCacheStatistics.getCacheGets();
long putsCnt = myCacheStatistics.getCachePuts();
long removalsCnt = myCacheStatistics.getCacheRemovals();
long missesCnt = myCacheStatistics.getCacheMisses();
long evictionsCnt = myCacheStatistics.getCacheEvictions();
long crtExpiredCnt = myCacheStatistics.getCacheExpirations();
System.out.println("getsCnt = "+getsCnt);
System.out.println("putsCnt = "+putsCnt);
System.out.println("removalsCnt = "+removalsCnt);
System.out.println("missesCnt = "+missesCnt);
System.out.println("evictionsCnt = "+evictionsCnt);
System.out.println("expiredCnt = "+expiredCnt);
System.out.println("hitPercentage = "+hitPercentage);
System.out.println("missPercentage = "+missPercentage);
System.out.println("Computed number of items in cache = "+(putsCnt-removalsCnt-expiredCnt-evictionsCnt));
}
@SuppressWarnings("unchecked")
// we are aware about the unchecked cast - it is a desired behavior.
// Cache can store objects of various types, so compile time type safety cannot be achieved easily.
// We'll get runtime ClassCastException if cache is used incorrectly.
public static <T> T get(String key) {
EhcacheValue<T> ehcacheValue = (EhcacheValue<T>)myCache.get(key);
return (T) (ehcacheValue!=null?ehcacheValue.getObject():null);
}
// we are aware about the unchecked cast - it is a desired behavior.
// Cache can store objects of various types, so compile time type safety cannot be achieved easily.
// We'll get runtime ClassCastException if cache is used incorrectly.
public static <T extends Object> T put(String key, T value, int timeToLiveInSeconds) {
if (key == null) {
throw new AssertionError("Key must not be null!");
}
if (value != null) {
EhcacheValue<T> ehcacheValue = new EhcacheValue<T>(value, Duration.of(60, ChronoUnit.SECONDS));
myCache.put(key, ehcacheValue);
return value;
} else {
return null;
}
}
}
import java.time.Duration;
导入java.util.function.Supplier;
导入org.ehcache.expiry.ExpiryPolicy;
公共类CustomExpiryPolicy这就是你要找的吗?所以在Ehcach3x中基本上没有能力在运行时定义每个元素的到期日,对吗?也就是说,您可以为缓存设置某种“默认过期”设置,但如果某些元素需要自定义过期,则无法将其设置为3x。正确吗?您不能在映射本身的级别上执行此操作,对吗。但是,您可以通过自定义过期来完成,因为在询问过期期限时,您会看到键和值。
<cache alias="myCache">
<expiry>
<ttl unit="seconds">20</ttl>
</expiry>
<heap>100</heap>
</cache>
public interface Expiry<K, V> {
Duration getExpiryForCreation(K key, V value);
Duration getExpiryForAccess(K key, ValueSupplier<? extends V> value);
Duration getExpiryForUpdate(K key, ValueSupplier<? extends V> oldValue, V newValue);
}
CacheManager cacheManager = CacheManagerBuilder.newCacheManagerBuilder().withCache("AllCache",
CacheConfigurationBuilder.newCacheConfigurationBuilder(String.class,String.class,
ResourcePoolsBuilder.heap(100))
.withExpiry(Expirations.timeToLiveExpiration(new Duration(86400, TimeUnit.SECONDS)))
.build()).build(true);
Cache<String, String> allCache = cacheManager.getCache("AllCache", String.class, String.class);
import java.io.Serializable;
import java.time.Duration;
public class EhcacheValue<T> implements Serializable {
private static final long serialVersionUID = 1L;
private T object;
private long timeToLive;
public EhcacheValue(T theObject, Duration theDuration) {
object = theObject;
timeToLive = theDuration.getSeconds();
}
public Duration getTimeToLiveDuration() {
return Duration.ofSeconds(timeToLive);
}
public T getObject() {
return object;
}
public void setObject(T theObject) {
object = theObject;
}
public long getTimeToLive() {
return timeToLive;
}
public void setTimeToLive(long theTimeToLive) {
timeToLive = theTimeToLive;
}
}
import java.time.Duration;
import java.util.function.Supplier;
import org.ehcache.expiry.ExpiryPolicy;
public class CustomExpiryPolicy<K, V extends EhcacheValue<?>> implements ExpiryPolicy<K, V> {
public CustomExpiryPolicy() {
}
@Override
public Duration getExpiryForCreation(K theKey, V theValue) {
return theValue.getTimeToLiveDuration();
}
@Override
public Duration getExpiryForAccess(K theKey, Supplier<? extends V> theValue) {
return null;
}
@Override
public Duration getExpiryForUpdate(K theKey, Supplier<? extends V> theOldValue, V theNewValue) {
return theNewValue.getTimeToLiveDuration();
}
}
public class TestEhCache {
private static final String CACHE_TIER_HEAP = "OnHeap";
public static void main(String[] args) {
StatisticsService statisticsService = new DefaultStatisticsService();
myCacheManager = CacheManagerBuilder.newCacheManagerBuilder()
.using(statisticsService)
.build();
//we init it here, not with boolean in build()
myCacheManager.init();
// Beware, the items are not expiring automatically, there are more mechanism in place for checking the expiration
// For instance the expiration is checked at get time
// for more details see the documentation from the version 2.8
// here: https://www.ehcache.org/documentation/2.8/apis/cache-event-listeners.html
// Unfortunately for the version 3.x doesn't exist a detailed depiction, but in main the procedure is the same
//
// Ehcache 2.8 documentation:
// Elements are checked for expiry in Ehcache at the following times:
//
// When a get request is made
// When an element is spooled to the diskStore in accordance with a MemoryStore eviction policy
// In the DiskStore when the expiry thread runs, which by default is
// net.sf.ehcache.Cache#DEFAULT_EXPIRY_THREAD_INTERVAL_SECONDS
CustomExpiryPolicy<String,EhcacheValue<?>> expiryPolicy = new CustomExpiryPolicy<String,EhcacheValue<?>>();
ResourcePools resourcePools = ResourcePoolsBuilder.newResourcePoolsBuilder().heap(2000L, EntryUnit.ENTRIES).build();
@SuppressWarnings("unchecked")
Class<EhcacheValue<?>> myEhcacheValue = (Class<EhcacheValue<?>>)(Class<?>)EhcacheValue.class;
CacheConfiguration<String,EhcacheValue<?>> cacheConfiguration = CacheConfigurationBuilder
.newCacheConfigurationBuilder(String.class, myEhcacheValue, resourcePools)
.withExpiry(expiryPolicy)
//.withService(new StoreStatisticsConfiguration(true)) // explicitly enable statistics, it seems is not needed
.build();
myCache = myCacheManager.createCache("myCache", cacheConfiguration);
myCacheStatistics = statisticsService.getCacheStatistics("myCache");
long cacheEntriesNr = myCacheStatistics.getTierStatistics().get(CACHE_TIER_HEAP).getMappings();
//nb element in heap tier
long sizeEntriesByStatistics = myCacheStatistics.getTierStatistics().get("OnHeap").getMappings();
//size of the tier in memory, when you set memory limits, not in this case
//long sizeBytesByStatistics = myCacheStatistics.getTierStatistics().get("OnHeap").getOccupiedByteSize();
long getsCnt = myCacheStatistics.getCacheGets();
long putsCnt = myCacheStatistics.getCachePuts();
long removalsCnt = myCacheStatistics.getCacheRemovals();
long missesCnt = myCacheStatistics.getCacheMisses();
long evictionsCnt = myCacheStatistics.getCacheEvictions();
long crtExpiredCnt = myCacheStatistics.getCacheExpirations();
System.out.println("getsCnt = "+getsCnt);
System.out.println("putsCnt = "+putsCnt);
System.out.println("removalsCnt = "+removalsCnt);
System.out.println("missesCnt = "+missesCnt);
System.out.println("evictionsCnt = "+evictionsCnt);
System.out.println("expiredCnt = "+expiredCnt);
System.out.println("hitPercentage = "+hitPercentage);
System.out.println("missPercentage = "+missPercentage);
System.out.println("Computed number of items in cache = "+(putsCnt-removalsCnt-expiredCnt-evictionsCnt));
}
@SuppressWarnings("unchecked")
// we are aware about the unchecked cast - it is a desired behavior.
// Cache can store objects of various types, so compile time type safety cannot be achieved easily.
// We'll get runtime ClassCastException if cache is used incorrectly.
public static <T> T get(String key) {
EhcacheValue<T> ehcacheValue = (EhcacheValue<T>)myCache.get(key);
return (T) (ehcacheValue!=null?ehcacheValue.getObject():null);
}
// we are aware about the unchecked cast - it is a desired behavior.
// Cache can store objects of various types, so compile time type safety cannot be achieved easily.
// We'll get runtime ClassCastException if cache is used incorrectly.
public static <T extends Object> T put(String key, T value, int timeToLiveInSeconds) {
if (key == null) {
throw new AssertionError("Key must not be null!");
}
if (value != null) {
EhcacheValue<T> ehcacheValue = new EhcacheValue<T>(value, Duration.of(60, ChronoUnit.SECONDS));
myCache.put(key, ehcacheValue);
return value;
} else {
return null;
}
}
}