对于频繁查看的表记录,且表数据不进行增删改操作,可以在项目启动的时候,将表数据加载到内存中。
数据缓存机制思路
1. WEB-INFO配置project-servlet.xml
<bean id="cacheLoader" class="com.spring.sc.project.support.CacheLoader"></bean>
2. 缓存加载类:CacheLoader.java
public class CacheLoader implements ApplicationContextAware {
@Override
public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
logger.info("加载字典表缓存开始");
dictService.loaderDicToCache();
logger.info("加载字典表缓存结束");
}
}
3. 缓存数据处理:DictService.java
/**
* 加载字典加入缓存
*/
@Override
public void loaderDictToCache() {
List<Dict> dictList = dictDao.findDictList();
if(dictList != null && !dictList.isEmpty()){
Map<String, List<Dict>> dictMap = new HashMap<>();
for(Dict dict : dictList){
List<Dict> dicts = dictMap.get(dict.getDsType());
if(dicts == null){
dicts = new ArrayList<>();
dictMap.put(dict.getDsType(),dicts);
}
dicts.add(dict);
}
for (String dsType : dictMap.keySet()) {
CachedObjectUtil.put(dsType, dictMap.get(dsType),dsType);
}
}
}
/**
* 根据字典类型获取字典
*/
@Override
public List<Dict> getDictByDsType(String dsType) {
return CachedObjectUtil.get(dsType,dsType,List.class);
}
4. 缓存工具类:CacheObjUtil.java
public class CacheObjUtil
{
/**
* 缓存管理器
*/
private static CacheManager cacheManager =CacheManager.create();
private CacheObjUtil(){};
/**
* 保存对象
* @param key 对象在缓存中的key
* @param value 对象在缓存中的value
* @param cacheName 保存缓存对象的类型
*/
public static void put(String key, Object value,String cacheName, boolean eternal, long timeToLiveSeconds, long timeToIdleSeconds)
{
if(!cacheManager.cacheExists(cacheName)) {
Cache cache = new Cache(cacheName, 200, false, eternal, timeToLiveSeconds, timeToIdleSeconds);
cacheManager.addCache(cache);
}
Cache cache=cacheManager.getCache(cacheName);
cache.put(new Element(key,value));
}
/**
* 获取对象
* @param key 对象在缓存中的key
* @param cacheName 保存缓存对象的类型
*/
public static <T> T get(String key,String cacheName,Class<T> t)
{
if(!cacheManager.cacheExists(cacheName)) {
return null;
}
Cache cache = cacheManager.getCache(cacheName);
Element element = cache.getQuiet(key);
if (element != null && !element.isExpired()) {
Object obj=element.getValue();
if(obj!=null){
return (T)obj;
}
}
return null;
}
}