spring框架使用EhCache本地缓存数据工具类

第一步:spring.xml配置CacheManager。

<?xml version="1.0" encoding="UTF-8"?>

<bean id="springCacheManager" class="org.springframework.cache.ehcache.EhCacheCacheManager">
    <property name="cacheManager" ref="ehcacheManager"/>
</bean>

<!--ehcache-->
<bean id="ehcacheManager" class="org.springframework.cache.ehcache.EhCacheManagerFactoryBean">
    <property name="configLocation" value="classpath:properties/ehcache.xml"/>
</bean>
第二步:配置ehcache.xml配置缓存设置。 <?xml version="1.0" encoding="UTF-8"?>

<diskStore path="C:\\ehcache\\cache"/>
<!-- <diskStore path=" /application/skscache"/> -->

<cache name="authorizationCache"
	maxEntriesLocalHeap="2000"
	eternal="false"
	timeToIdleSeconds="3600"
	timeToLiveSeconds="0"
	overflowToDisk="false"
	statistics="true">
</cache>


<defaultCache  
	maxElementsInMemory="1000"  
	eternal="false"  
	timeToIdleSeconds="120"  
	timeToLiveSeconds="120"  
	overflowToDisk="true"  
	maxElementsOnDisk="10000"  
	diskSpoolBufferSizeMB="30"  
	diskPersistent="false"  
	diskExpiryThreadIntervalSeconds="120"  
	memoryStoreEvictionPolicy="LRU"  
	statistics="false"  
	/>  

<cache name="invoiceFpKeyCache"  
	maxElementsInMemory="1000"  
	maxElementsOnDisk="10000"  
	eternal="false"  
	overflowToDisk="true"  
	diskSpoolBufferSizeMB="20"  
	timeToIdleSeconds="20"  
	timeToLiveSeconds="20"
	memoryStoreEvictionPolicy="LFU"  
	transactionalMode="off"  
	/>
	
<cache name="invoiceFpqqlshCache"  
	maxElementsInMemory="1000"  
	maxElementsOnDisk="10000"  
	eternal="false"  
	overflowToDisk="true"  
	diskSpoolBufferSizeMB="20"  
	timeToIdleSeconds="6"  
	timeToLiveSeconds="6"  
	memoryStoreEvictionPolicy="LFU"  
	transactionalMode="off"  
	/>
参数说明:

:当内存缓存中对象数量超过maxElementsInMemory时,将缓存对象写到磁盘缓存中(需对象实现序列化接口)。

:用来配置磁盘缓存使用的物理路径,Ehcache磁盘缓存使用的文件后缀名是*.data和*.index。

name:缓存名称,cache的唯一标识(ehcache会把这个cache放到HashMap里)。

maxElementsOnDisk:磁盘缓存中最多可以存放的元素数量,0表示无穷大。

maxElementsInMemory:内存缓存中最多可以存放的元素数量,若放入Cache中的元素超过这个数值,则有以下两种情况。

1)若overflowToDisk=true,则会将Cache中多出的元素放入磁盘文件中。

2)若overflowToDisk=false,则根据memoryStoreEvictionPolicy策略替换Cache中原有的元素。

Eternal:缓存中对象是否永久有效,即是否永驻内存,true时将忽略timeToIdleSeconds和timeToLiveSeconds。

timeToIdleSeconds:缓存数据在失效前的允许闲置时间(单位:秒),仅当eternal=false时使用,默认值是0表示可闲置时间无穷大,此为可选属性即访问这个cache中元素的最大间隔时间,若超过这个时间没有访问此Cache中的某个元素,那么此元素将被从Cache中清除。

timeToLiveSeconds:缓存数据在失效前的允许存活时间(单位:秒),仅当eternal=false时使用,默认值是0表示可存活时间无穷大,即Cache中的某元素从创建到清楚的生存时间,也就是说从创建开始计时,当超过这个时间时,此元素将从Cache中清除。

overflowToDisk:内存不足时,是否启用磁盘缓存(即内存中对象数量达到maxElementsInMemory时,Ehcache会将对象写到磁盘中),会根据标签中path值查找对应的属性值,写入磁盘的文件会放在path文件夹下,文件的名称是cache的名称,后缀名是data。

diskPersistent:是否持久化磁盘缓存,当这个属性的值为true时,系统在初始化时会在磁盘中查找文件名为cache名称,后缀名为index的文件,这个文件中存放了已经持久化在磁盘中的cache的index,找到后会把cache加载到内存,要想把cache真正持久化到磁盘,写程序时注意执行net.sf.ehcache.Cache.put(Element element)后要调用flush()方法。

diskExpiryThreadIntervalSeconds:磁盘缓存的清理线程运行间隔,默认是120秒。

diskSpoolBufferSizeMB:设置DiskStore(磁盘缓存)的缓存区大小,默认是30MB

memoryStoreEvictionPolicy:内存存储与释放策略,即达到maxElementsInMemory限制时,Ehcache会根据指定策略清理内存,共有三种策略,分别为LRU(最近最少使用)、LFU(最常用的)、FIFO(先进先出)。

第三步:工具类代码。

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cache.Cache;
import org.springframework.cache.CacheManager;
import org.springframework.stereotype.Component;

import com.whty.framework.base.util.CheckEmptyUtil;

/**

  • ehCache工具类

*/
@Component
public class EhcacheUtil {

@Autowired
private CacheManager cacheManager;

public static final String INVOICE_PFDM_FPHM_CACHE = "invoiceFpKeyCache";

public static final String FPQQLSH_CACHE = "invoiceFpqqlshCache";

/**
 * List添加数据
 * 
 * @param key
 */
@SuppressWarnings("unchecked")
public void add(String cacheName, String value) {
	Cache cache = cacheManager.getCache(cacheName);
	List<String> list = cache.get(cacheName, ArrayList.class);
	if (CheckEmptyUtil.isEmpty(list)) {
		list = new ArrayList<>();
	}
	list.add(value);
	cache.put(cacheName, list);
}

/**
 * List获取数据
 * 
 * @param key
 * @return String
 */
@SuppressWarnings("unchecked")
public List<String> get(String cacheName) {
	Cache cache = cacheManager.getCache(cacheName);
	List<String> list = cache.get(cacheName, ArrayList.class);
	if (CheckEmptyUtil.isEmpty(list)) {
		return null;
	}
	return list;
}

/**
 * List判断是否包含数据
 * 
 * @param key
 * @return String
 */
@SuppressWarnings("unchecked")
public boolean contains(String cacheName, String value) {
	Cache cache = cacheManager.getCache(cacheName);
	List<String> list = cache.get(cacheName, ArrayList.class);
	if (CheckEmptyUtil.isEmpty(list)) {
		return false;
	}
	return list.contains(value);
}

/**
 * List删除数据
 * 
 * @param cacheName
 * @param key
 *            void
 */
@SuppressWarnings("unchecked")
public void remove(String cacheName, String value) {
	Cache cache = cacheManager.getCache(cacheName);
	List<String> list = cache.get(cacheName, ArrayList.class);
	if (CheckEmptyUtil.isEmpty(list)) {
		return;
	}
	list.remove(value);
	cache.put(cacheName, list);
}

/**
 * Map添加数据
 * 
 * @param key
 */
@SuppressWarnings("unchecked")
public void put(String cacheName, String key, String value) {
	Cache cache = cacheManager.getCache(cacheName);
	Map<String, String> map = cache.get(cacheName, HashMap.class);
	if (CheckEmptyUtil.isEmpty(map)) {
		map = new HashMap<>();
	}
	map.put(key, value);
	cache.put(cacheName, map);
}

/**
 * Map获取数据
 * 
 * @param key
 * @return String
 */
@SuppressWarnings("unchecked")
public String get(String cacheName, String key) {
	Cache cache = cacheManager.getCache(cacheName);
	Map<String, String> map = cache.get(cacheName, HashMap.class);
	if (CheckEmptyUtil.isEmpty(map)) {
		return null;
	}
	return map.get(key);
}

/**
 * Map获取数据
 * 
 * @param key
 * @return String
 */
@SuppressWarnings("unchecked")
public List<String> getValues(String cacheName) {
	Cache cache = cacheManager.getCache(cacheName);
	Map<String, String> map = cache.get(cacheName, HashMap.class);
	if (CheckEmptyUtil.isEmpty(map)) {
		return null;
	}
	List<String> values = new ArrayList<>(map.size());
	for (Entry<String, String> entry : map.entrySet()) {
		values.add(entry.getValue());
	}
	return values;
}

/**
 * Map判断是否包含数据
 * 
 * @param key
 * @return String
 */
@SuppressWarnings("unchecked")
public boolean containsKey(String cacheName, String key) {
	Cache cache = cacheManager.getCache(cacheName);
	Map<String, String> map = cache.get(cacheName, HashMap.class);
	if (CheckEmptyUtil.isEmpty(map)) {
		return false;
	}
	return map.containsKey(key);
}

/**
 * Map删除数据
 * 
 * @param cacheName
 * @param key
 *            void
 */
@SuppressWarnings("unchecked")
public void removeKey(String cacheName, String key) {
	Cache cache = cacheManager.getCache(cacheName);
	Map<String, String> map = cache.get(cacheName, HashMap.class);
	if (CheckEmptyUtil.isEmpty(map)) {
		return;
	}
	map.remove(key);
	cache.put(cacheName, map);
}

}
注意:此处的cacheName 要和ehcahe.xml中的名称保持一致。

参考文档:

https://blog.csdn.net/clj198606061111/article/details/41121437

作者:itget
来源:CSDN
原文:https://blog.csdn.net/hu582205/article/details/80585529
版权声明:本文为博主原创文章,转载请附上博文链接!

猜你喜欢

转载自blog.csdn.net/tongshuixu8025/article/details/88362818