Skip to content
DAILY QUOTE

“ ”

需求:利用Redis的Set集合求交集,实现共同关注功能。在博主个人页面展示出当前用户与博主的共同好友

  • 代码实现:修改关注与取关接口代码,在更新数据库的同时,将用户关注的id记录到Redis的Set集合中;新增查询目标用户的共同关注接口,求两个用户的Set集合的交集,即为共同关注。
java
/**
 * 关注或取关用户。
 *
 * 作用:
 * 1.获取登录用户;
 * 2.关注,新增数据;
 * 3.把关注用户的id,放入Redis的Set集合sadduserIdfollowerUs;
 * 4.取关,删除deletefromtb_followwhereuser_id=?andf;
 * 5.把关注用户的id从Redis集合中移除;
 *
 * @param followUserId被关注用户id
 * @param isFollow是否关注
 * @return处理结果
 */
@Override
public Result follow(Long followUserId, Boolean isFollow) {
    //1.获取登录用户
    Long userId = UserHolder.getUser().getId();
    String key="follows:"+userId;
    if(isFollow){
        //2.关注,新增数据
        Follow follow = new Follow();
        follow.setUserId(userId);
        follow.setFollowUserId(followUserId);
        boolean isSuccess=save(follow);
        if(isSuccess){
            //把关注用户id放入Redis的Set集合
            stringRedisTemplate.opsForSet().add(key,followUserId.toString());
        }
    } else {
        //3.取关,删除delete from tb_follow where user_id=? and follow_user_id=?
        boolean isSuccess = remove(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", followUserId));
        if(isSuccess){
            //把关注用户的id从Redis集合中移除
            stringRedisTemplate.opsForSet().remove(key,followUserId.toString());
        }
    }
    return Result.ok();
}


/**
 * 查询当前用户和目标用户的共同关注。
 *
 * 作用:
 * 1.获取当前用户;
 * 2.求交集;
 * 3.无交集;
 * 4.解析id集合;
 * 5.查询用户;
 *
 * @param id业务id
 * @return处理结果
 */
@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.isEmpty()||intersect==null){
        //无交集
        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);
}
  • 功能测试

用户1014关注了用户2与用户1012

用户2关注了用户1012

用户1014查看用户2可以知道用户1014与用户2的共同关注