Redis 实现销量统计和已读未读功能
本文主要讨论,通过Redis实现:1. 商品的销量统计。2. 页面内容的已读/未读功能
销量统计
背景
实现统计商品的购买量(热度)。
假设有如下商品信息:
要按照年度、月度、总销量对商品进行排序输出。
实现
采用Redis中的zSet数据结构,以商品id作为value,商品购买数量作为score,利用zSet的排序功能可以快速得到销量排行信息。
要实现按不同维度(年、月、所有)统计销量,就需要3个zSet。
所有数据:key={NAME_SPACE}:ALL
年度数据:key={NAME_SPACE}:{year}
月度数据:key={NAME_SPACE}:{year}{month}
购买
用户每购买一件商品就把商品id存入zSet,并增加score,score就是商品的购买次数。
/**
* 购买一件商品,将商品信息写入redis中对应的 zSet
*
* @param goodsId goodsId
*/
@Override
public boolean buy(String goodsId) {
if (!goodsIdSet.contains(goodsId)) {
throw new IllegalArgumentException("goods id error:" + goodsId);
}
LocalDate today = LocalDate.now();
String monthKey = getRedisKey(today.getYear(), today.getMonthValue());
String yearKey = getRedisKey(today.getYear(), 0);
String allKey = getRedisKey(0, 0);
//分别增加 月、年、所有 中的数据
zSetOperations.incrementScore(monthKey, goodsId, 1.0);
zSetOperations.incrementScore(yearKey, goodsId, 1.0);
zSetOperations.incrementScore(allKey, goodsId, 1.0);</