Redis实现关注取消关注,展示共同关注及Feed流
关注:分析业务需求
思路:
那么全部用数据库来实现,方便吗?
纯数据库:两个select找,再判断交集,这样显然是低效和缓慢的
所以,我们用redis来进行优化。
步骤:
这样,我们就可以快速的实现业务了。
流程图:
代码:
@Override
public Result followCommons(Long id) {
// 1.获取当前用户
Long userId = UserHolder.getUser().getId();
String key = "follows:" + userId;
// 2.求交集
String key2 = "follows:" + id;
Set<String> intersect = stringRedisTemplate.opsForSet().intersect(key, key2);
if (intersect == null || intersect.isEmpty()) {
// 无交集
return Result.ok(Collections.emptyList());
}
// 3.解析id集合
List<Long> ids = intersect.stream().map(Long::valueOf).collect(Collectors.toList());
// 4.查询用户
List<UserDTO> users = userService.listByIds(ids)
.stream()
.map(user -> BeanUtil.copyProperties(user, UserDTO.class))
.collect(Collectors.toList());
return Result.ok(users);
}
feed流
什么是feed流?
当然,我们小白做智能排序还是有点难度,所以,这次我们就按timeline来进行初步的理解。
Feed流有三种模式:
1.模式
优点:节省内存空间
缺点:耗时久
2.推模式
推模式相比拉模式,去掉了发件箱,当博主发布文章时,直接推送到粉丝的收件箱中
优点:耗时低
缺点:内存占用高
3.推拉结合模式
将粉丝多的大v使用拉模式,对于粉丝数量少的使用拉模式
一般软件由于流量少,一般是采用推模式,大厂软件流量高,采用推拉结合模式
推模式代码实现:
// 4.推送笔记id给所有粉丝
for (Follow follow : follows) {
// 4.1.获取粉丝id
Long userId = follow.getUserId();
// 4.2.推送
String key = FEED_KEY + userId;
stringRedisTemplate.opsForZSet().add(key, blog.getId().toString(), System.currentTimeMillis());
}
// 5.返回id
下一篇:
Redis实现用户关注功能
