写在前面
taobao-pamirs-proxycache 是一款开源缓存代理框架, 它将 缓存代码 与 业务代码 解耦。让开发专注coding业务, 缓存通过xml配置即可实现。本文先从此工具如何使用讲起,给大家带来点感知~再从源码剖析它的实现原理。
一、proxycache工具的感知
1.1 使用场景
假设我有这样的一个场景,在访问UserWhiteReadService.getUserWhiteByAppAndWhiteCode时,希望先从缓存获取,结果为空,则走原生方法,再把原生方法返回的结果put到缓存。传统的做法,会写一堆取缓存再判空等代码。方法多了的话,每个要缓存的方法需要重复上述coding。结合这种场景,使用taobao-pamirs-proxycache 能给我们带来什么好处。从下面的代码来看,业务代码中去除了缓存的相关代码。只需要配置下xml即可达到传统做法的目的。管理更加集中了。
public ResultSupport<List<UserWhiteEventDTO>> getUserWhiteByAppAndWhiteCode(String appName, String userWhiteCode) throws Exception {
ResultSupport<List<UserWhiteEventDTO>> res = new ResultSupport<List<UserWhiteEventDTO>>();
try {
List<UserWhiteEventDO> r = userWhiteEventDAO.selectUserWhitesByAppAndWhiteCode(appName, userWhiteCode);
res.setModule(TransferUtils.convert2UserWhiteEventDTOList(r));
res.setSuccess(Boolean.TRUE);
} catch (Exception e) {
res.setMessage("异常 : " + e);
throw new Exception("UserWhiteReadServiceImpl.getUserWhiteByAppAndWhiteCode error : " + e);
}
return res;
}
缓存、清理方法配置 biz-cache.xml
<?xml version="1.0" encoding="gb2312"?>
<cacheModule>
<!-- 缓存bean list -->
<cacheBeans>
<cacheBean>
<beanName>userWhiteReadService</beanName>
<cacheMethods>
<methodConfig>
<methodName>getUserWhiteByAppAndWhiteCode</methodName>
<expiredTime>2592000</expiredTime><!-- 指定缓存生命周期 -->
</methodConfig>
<methodConfig>
<methodName>getUserWhitesByUserId</methodName>
<expiredTime>2592000</expiredTime><!-- 指定缓存生命周期 -->
</methodConfig>
</cacheMethods>
</cacheBean>
</cacheBeans>
<!-- 清缓存bean list -->