版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_32534855/article/details/85597871
1.目的
背景:文章量6000条左右,用户量170w多
在考虑用户频繁查询数据库这一块吗,我们在数据库与java程序之间介入了redis缓存
2.知识储备
1.redis:hash结构
- 资料:http://www.runoob.com/redis/redis-strings.html
- 原因:hash就像数据库一样,我们把文章id作为key,value作为文章内容的载体
- 用到的方法:
2.redis:string结构
- 资料:http://www.runoob.com/redis/redis-hashes.html
- 原因:我们把文章id,与用户推荐过文章列表存储在这里
- 用到的方法:
3.实现
1.我们把最新文章前1000条数分别存入hash,与string结构中
//从db查询出来的文章列表
List articleList = new ArrayList();
//获取文章id列表
List<Integer> ids = articleList .stream().map(z->{return z.getInt("id");}).collect(Collectors.toList());
//文章放入缓存中
jedis.hmset("articleList", articleList);
//文章id放入缓存中
jedis.set("articleIdList", ids);
2.查询最新文章实现
//获取用户推荐过文章列表
List<Integer> hasRecommendList = jedis.get("hasRecommedArticle"+userId);
//获取推荐文章id列表
List<Integer> recommendList = jedis.get("articleIdList");
//做推荐文章列表 与 用户推荐过文章列表差集
recommendList.removaAll(hasRecommendList);
//查询文章id,不用subList的原因:subList没有序列化
List selectIdList = new ArrayList();
for (int i = 0; i < 5; i++) {
selectIdList.add(recommendList.get(i));
}
//查询文章
List retrunList = jedis.hmget("articleList",selectIdList.toArray());