内容一:选择的数据结构同样也是哈希!!
内容二:用户的维度~存储点赞过的历史文章(其中为了减少二次加工,对Field做了小技巧的处理..)~存储的逻辑要适用于"点赞"与“取消点赞"的场景
内容:直接从缓存的SortedSet获取即可,获取出Field后,需要作分隔符的小处理
以用户为维度,缓存用户点赞过的历史文章
key=存储到redis的标志符;field=用户id-文章id,value=文章标题
PraiseService.java
private void cacheUserPraiseArticle(final PraiseDto dto,Boolean isOn){
final String fieldKey=dto.getUserId()+SplitChar+dto.getArticleId();
HashOperations<String,String,String> hash=redisTemplate.opsForHash();
if (isOn){
hash.put(Constant.RedisArticleUserPraiseKey,fieldKey,dto.getTitle());
}else{
hash.put(Constant.RedisArticleUserPraiseKey,fieldKey,"");
}
}
//以用户为维度~获取用户详情以及点赞过的历史文章
public Map<String,Object> getUserArticles(final Integer currUserId) throws Exception{
Map<String,Object> resMap=Maps.newHashMap();
//用户详情-直接db查询
resMap.put("userInfo~用户详情",userMapper.selectByPrimaryKey(currUserId));
//用户点赞过的历史文章-查redis的hash
List<PraiseDto> userArticles=Lists.newLinkedList();
HashOperations<String,String,String> hash=redisTemplate.opsForHash();
//field-value对
Map<String,String> map=hash.entries(Constant.RedisArticleUserPraiseKey);
for (Map.Entry<String, String> entry:map.entrySet()){
String field=entry.getKey();//用户ID-文章ID
String value=entry.getValue();//文章标题
String[] arr=StringUtils.split(field,SplitChar);
//判断 “文章标题是否为空” - 如果为空,则代表已经取消点赞了
if (StringUtils.isNotBlank(value)){
//判断当前 arr[0] 是否为当前用户id,如果是,则代表 arr[1] 为当前用户点赞过的文章id
if (currUserId.toString().equals(arr[0])){
userArticles.add(new PraiseDto(currUserId,Integer.valueOf(arr[1]),value));
}
}
}
resMap.put("userPraiseArticles~用户点赞过的历史文章",userArticles);
return resMap;
}