最近由于公司业务,需要对用户邀请新人做排名统计,开始用了sql做了统计展示,后觉得每次刷新排行榜都需要去数据库中查询,不仅影响性能,效率可能也不是很好。后了解到可以使用redis zset做排名统计,故此记录。
/**
* 功能描述 将数据缓存到redis中
* @author zm
* @date 2019/9/23 10:15
* @param userInfo count
* @return void
*/
private void setRedisUserRankInfo(UserInfo userInfo, Integer count){
try {
Map<String, Object> userInfoMap = new HashMap<>();
userInfoMap.put("nickName",userInfo.getUserName());
userInfoMap.put("headImg", userInfo.getAvatar());
redisTemplate.opsForZSet().add(REDISKEY,userInfo.getUserId(),count.doubleValue());
redisTemplate.opsForValue().set(REDISKEY+"_"+userInfo.getUserId(),JSON.toJSONString(userInfoMap));
} catch (Exception e) {
log.error("信息存入redis异常",e);
}
}
/**
* 功能描述 获取排行榜
* @author zm
* @date 2019/9/23 10:27
* @param
* @return java.util.List<java.util.Map<java.lang.String,java.lang.Object>>
*/
private List<Map<String,Object>> getRankList(){
List<Map<String,Object>> rank = new ArrayList<>();
Set<ZSetOperations.TypedTuple<String>> typedTuples = redisTemplate.opsForZSet().reverseRangeByScoreWithScores(REDISKEY, 0, 99999, 0, 10);//只取前十条
int index = 0;
for(ZSetOperations.TypedTuple typle:typedTuples){
Map<String, Object> userRankMap = new HashMap<>();
userRankMap.put("userId",typle.getValue());
userRankMap.put("count",typle.getScore().intValue());
userRankMap.put("rank",++index);
String userInfo = redisTemplate.opsForValue().get(REDISKEY+ "_" + typle.getValue());
if(StringUtils.isNotBlank(userInfo)){
Map userInfoMap = JSON.parseObject(userInfo, HashMap.class);
userRankMap.put("nickName",userInfoMap.get("nickName"));
userRankMap.put("headImg",userInfoMap.get("headImg"));
}
rank.add(userRankMap);
}
return rank;
}
/**
* 功能描述 获取 我的 排名信息
* @author zm
* @date 2019/9/23 10:42
* @param userId
* @return java.util.Map<java.lang.String,java.lang.Object>
*/
private Map<String,Object> getUserRank(String userId){
Long userRank = redisTemplate.opsForZSet().reverseRank(REDISKEY, userId);//我的排名
Double count = redisTemplate.opsForZSet().score(REDISKEY, userId);//我的分数
Map<String, Object> userRankMap = new HashMap<>();
userRankMap.put("userId",userId);
if(userRank ==null || agentCount ==null){
return null;
}
userRankMap.put("count",count.intValue());
userRankMap.put("rank",userRank+1);
String userInfo = redisTemplate.opsForValue().get(REDISKEY+ "_" + userId);
if(StringUtils.isNotBlank(userInfo)){
Map userInfoMap = JSON.parseObject(userInfo, HashMap.class);
userRankMap.put("nickName",userInfoMap.get("nickName"));
userRankMap.put("headImg",userInfoMap.get("headImg"));
}
return userRankMap;
}
是不是比写sql简单太多了!!
redis zset,一块钱四个,嘿嘿!!