Redis实现互相关注功能

Redis实现互相关注功能

我们要实现关注功能,首先,我们需要得到关注的目标ID:

    @PutMapping("/{id}/{isFollow}")
    public Result followUser(@PathVariable("id") Long id,@PathVariable("isFollow") Boolean isFollow){
        return followService.followUser(id,isFollow);
    }

sql的建表为:
在这里插入图片描述
主键id,user_id为被关注者的id,follow_user_id为关注者的id。

CREATE TABLE `tb_follow` (
  `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '主键',
  `user_id` bigint(20) unsigned NOT NULL COMMENT '用户id',
  `follow_user_id` bigint(20) unsigned NOT NULL COMMENT '关联的用户id',
  `create_time` timestamp NOT NULL DEFAULT CURRENT_TIMESTAMP COMMENT '创建时间',
  PRIMARY KEY (`id`) USING BTREE
) ENGINE=InnoDB AUTO_INCREMENT=16 DEFAULT CHARSET=utf8mb4 ROW_FORMAT=COMPACT

对应的JavaBean对象

@Data
@EqualsAndHashCode(callSuper = false)
@Accessors(chain = true)
@TableName("tb_follow")
public class Follow implements Serializable {

    private static final long serialVersionUID = 1L;

    /**
     * 主键
     */
    @TableId(value = "id", type = IdType.AUTO)
    private Long id;

    /**
     * 用户id
     */
    private Long userId;

    /**
     * 关联的用户id
     */
    private Long followUserId;

    /**
     * 创建时间
     */
    private LocalDateTime createTime;


}

Redis存储的数据结构我们选用集合Set,我们先判断该用户是否关注过目标用户,如果没有关注,我们将信息封装到对象中,并将信息保存到数据库中。

        //先拿到当前的用户
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.fail("请先登录");
        }
        Long userId = user.getId();
        if(isFollow){
            //这里表示未关注过
            Follow follow = new Follow();
            follow.setFollowUserId(id);
            follow.setUserId(userId);
            boolean isSuccess = save(follow);
            if(isSuccess){
                stringRedisTemplate.opsForSet().add(RedisEnums.FOLLOW_USER_KEY +userId,id.toString());
            }
        }

我们用一个字符串拼接当前的用户ID,存储到Redis中
关注过就取消关注 先从数据库中删除,再从数据库中删除:

         else {
            boolean isSuccess = remove(new QueryWrapper<Follow>().eq("user_id", userId).eq("follow_user_id", id));
            if(isSuccess){
                stringRedisTemplate.opsForSet().remove(RedisEnums.FOLLOW_USER_KEY +userId,id.toString());
            }
        }

那么我们怎么判断当前用户是否关注过目标用户呢?
我们通过查找数据库查找是否有对应的数据:

        //先拿到当前的用户
        UserDTO user = UserHolder.getUser();
        if(user == null){
            return Result.fail("请先登录");
        }
        Long userId = user.getId();
        Integer count = query().eq("user_id", userId).eq("follow_user_id", id).count();
        return Result.ok(count > 0);

这样我们就完成了互相关注的功能。
我们去查询共同关注,拿到目标ID,去查询和当前用户的交集即可,取出的就是一个ID集合,我们将这个ID集合转换成用户的集合。

        //先拿到当前用户的Id
        UserDTO user = UserHolder.getUser();
        if (user == null) {
            return Result.fail("请先登录");
        }
        Long userId = user.getId();
        Set<String> idString = stringRedisTemplate.opsForSet().intersect(RedisEnums.FOLLOW_USER_KEY + id, RedisEnums.FOLLOW_USER_KEY + userId);
        if(idString == null){
            return Result.fail("没有");
        }
        //查询到用户的id集
        List<Long> ids = idString.stream()
                .map(Long::valueOf)
                .collect(Collectors.toList());
        List<UserDTO> users = userService.listByIds(ids)
                .stream()
                .map(user1 -> BeanUtil.copyProperties(user1, UserDTO.class))
                .collect(Collectors.toList());
        return Result.ok(users);

在Redis中进行交集操作:

sadd key1  1 2 3 4

sadd key2  1 2 5 6

sinter key1 key2

在这里插入图片描述

  • 1
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

爱敲键盘的程序源

你的激励是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值