本文主要讨论,通过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);
// do other thing
log.info("buy a goods: {}", goodsId);
return true;
}
直接取出对应维度的zSet,即可得到销量数据。
/**
* 按 年、月、所有 获取前n个商品的销量
*
* @param unit YEARS、MONTHS、FOREVER
* @param topCount 前n
* @return 前n个商品的销量
*/
@Override
public List<Goods> topOne(ChronoUnit unit, int topCount) {
log.info("getTopOne,unit: {},count: {}", unit, topCount);
LocalDate today = LocalDate.now();
String key;
switch (unit) {
case YEARS:
key = getRedisKey(today.getYear(), 0);
break;
case MONTHS:
key = getRedisKey(today.getYear(), today.getMonthValue());
break;
case FOREVER:
key = getRedisKey(0, 0);
break;
default:
throw new RuntimeException("unSupport unit: " + unit);
}
return getData(key, topCount);
}
/**
* 从zSet中获取数据,并转换成商品实体类
*
* @param key key
* @param topCount 前n
* @return 前n个商品的销量
*/
private List<Goods> getData(String key, int topCount) {
Set<ZSetOperations.TypedTuple<String>> tuples = zSetOperations.reverseRangeWithScores(key, 0, topCount - 1);
if (Objects.isNull(tuples)) {
return Collections.emptyList();
}
return tuples.stream()
.map(
tuple -> Goods.builder()
.id(tuple.getValue())
.name(goodsMap.get(tuple.getValue()).getName())
.saleCount(Objects.nonNull(tuple.getScore()) ? tuple.getScore().intValue() : 0)
.build()
).collect(Collectors.toList());
}
完整代码,请参考文末git仓库。
需要记录用户是否已经点击过某条数据。
采用Redis中zSet,以数据id为val,用户点击时的时间戳为score,数据结构如下:
key={NAME_SPACE}:{msgType}:{userId}
zSet: val={msgId} ; score={timestamp}
往zSet中存入数据:
public void read(MsgType msgType, String userId, String msgId) {
long timestamp = System.currentTimeMillis();
String key = getRedisKey(msgType, userId);
zSetOperations.add(key, msgId, timestamp);
log.info("read msg, add key:{}", key);
}
private String getRedisKey(MsgType msgType, String userId) {
return KeyUtils.concat(":", NAME_SPACE, msgType.ordinal(), userId);
}
从zSet中查询指定的val,判断其score与当前时间的差值,是否大于数据有效时间(TTL):
public boolean isRead(MsgType msgType, String userId, String msgId) {
String key = getRedisKey(msgType, userId);
log.info("check isRead, key:{}", key);
Double timestamp = zSetOperations.score(key, msgId);
if (Objects.isNull(timestamp)) {
//该消息id不存在,未读
return false;
}
long now = System.currentTimeMillis();
if (now - timestamp > msgType.getTtl()) {
//数据已经失效
evictExpireData(msgType, userId, msgId);
return false;
}
return true;
}
/**
* 清除过期的数据
*/
@SuppressWarnings("unchecked")
private void evictExpireData(MsgType msgType, String userId, String msgId) {
String key = getRedisKey(msgType, userId);
long now = System.currentTimeMillis();
log.info("remove data, from {}, to {}", 0, now - msgType.getTtl());
zSetOperations.removeRangeByScore(key, 0, now - msgType.getTtl());
}
https://gitee.com/thanksm/redis_learn/tree/master/topone