XStream实现缓存
************************************************************************************
系统实现缓存有多种方式,如redis,ehcache,Memcached,在项目开发中,使用另外一种实现方式使用xml配置文件和XStream方式实现缓存,原理是数据放在内存中。思路是:定义一个全局静态变量Map,将数据保存在map中即可。
************************************************************************************
步骤一:配置xml文件
<?xml version="1.0" encoding="UTF-8" ?>
<webcache>
<cache>
<name>CACHE_DICT</name>
<descript>数据字典</descript>
<datasource></datasource>
<sql><![CDATA[]]></sql>
<mapperid>vc.cache.mapper.CACHE_DICT</mapperid>
<type>DICT</type>
</cache>
</webcache>
步骤二:建对应的实体类
// XStream的别名注解,在xml文件对应标签名
@XStreamAlias("webcache")
public class WebCacheXmlBean {
// 集合注解,只能用在集合属性上
@XStreamImplicit
List<CacheXmlBean> cacheList;
public List<CacheXmlBean> getCacheList() {
return cacheList;
}
public void setCacheList(List<CacheXmlBean> cacheList) {
this.cacheList = cacheList;
}
}
@XStreamAlias("cache")
public class CacheXmlBean {
public static final String CACHE_TYPE_DICT = "DICT";
public static final String CACHE_TYPE_DATA = "DATA";
private String name;
private String descript;
private String datasource;
private String sql;
private String mapperid;
private String type;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getDescript() {
return descript;
}
public void setDescript(String descript) {
this.descript = descript;
}
public String getDatasource() {
return datasource;
}
public void setDatasource(String datasource) {
this.datasource = datasource;
}
public String getSql() {
return sql;
}
public void setSql(String sql) {
this.sql = sql;
}
public String getMapperid() {
return mapperid;
}
public void setMapperid(String mapperid) {
this.mapperid = mapperid;
}
public String getType() {
return type;
}
public void setType(String type) {
this.type = type;
}
}
步骤三:将xml配置信息转化为bean
public static Map<String, List> DATA_CACHES = new HashMap<>();
public void dictCache(){
XStream xStream = new XStream();
//自动扫描注解
xStream.autodetectAnnotations(true);
// 扫描实体类
xStream.processAnnotations(new Class[]{WebCacheXmlBean.class, CacheXmlBean.class});
File file = new File("f:/ETOM/pmms/pmms/src/test/resources/dict.xml");
WebCacheXmlBean webCacheXmlBean = (WebCacheXmlBean) xStream.fromXML(file);
List<CacheXmlBean> cacheXmlList = webCacheXmlBean.getCacheList();
for (CacheXmlBean cacheXmlBean : cacheXmlList) {
String cacheName = cacheXmlBean.getName();
String mapperid = cacheXmlBean.getMapperid();
String sql = cacheXmlBean.getSql();
List cacheList = null;
if(StringUtil.isNotEmpty(mapperid)){
cacheList = dao.find(mapperid);
}else if(StringUtil.isNotEmpty(sql)){
cacheList = dao.findBySQL(sql);
}
logger.info("load cache 【"+cacheName+"】");
if(cacheList != null){
DATA_CACHES.put(cacheName, cacheList);
}
}
}
有志之士,共同学习