本地缓存机制常被用来存储系统中变化频率不高的数据,常见的变化频率不高数据有:比如商品配置,可能商家的商品描述信息基本不变化,价格变化也不是很频繁,那可以存在缓存里减少访问数据库。又比如某类计算存在热数据,即某些问题的计算入参在短时间内频繁重,则可以把计算结果缓存起来。
设计了类似LRU+TOP K的思路,针对新来的请求先查缓存,若没有实时计算,并把结果添加到缓存,之后对缓存按照请求次数和最近访问时间排序(先按照时间由近到远,再按照请求次数由大到小,最终顺序为请求次数由大到小,次数相同的时间由近到远),每次更新后删除顺序值大于缓存SIZE的计算结果。
示例代码如下:
public class ComputeServiceWithCache {
private volatile Map<String, ComputeResult> resultCacheMap = new HashMap<String, ComputeResult>();
/** 已排序缓存列表(用于排序,维护在内存中,提高排序效率) */
private List<ComputeResult> cacheRankList = new ArrayList<ComputeResult>();
/** 计算服务 */
private ComputeService computeService;
/** 缓存大小 */
private static final int CACHE_SIZE = 100;
/** 数值1 */
private static final int ONE = 1;
/**
* 计算买卖双方的关系
*
* @param buyerId 买家ID
* @param sellerId 卖家ID
* @return 计算结果
*/
public ComputeResult computeRelation(String buyerId, String sellerId) {
String cacheKey = buyerId + sellerId;
ComputeResult result = findRelationInCache(cacheKey);
if (null == result) {
result = computeService.compute(buyerId, sellerId);