仿牛客网项目---关注模块的实现

news2024/10/6 8:28:58

本篇文章是关于我的项目的关注模块的开发。

关注模块的开发实现了用户之间的关注功能和关注列表的展示。通过使用相应的服务类处理关注和取消关注操作,并利用用户服务类获取用户信息,实现了关注功能的存储和查询。同时,通过触发关注事件,实现了关注操作的异步处理。在控制器类中,处理了关注和取消关注的请求,并展示了用户关注的人列表和粉丝列表。该模块的开发使得关注功能具备了高效、可靠和可扩展的特性,为用户之间的关联和互动提供了支持。

我们先来写RedisKeyUtil这个文件。

上篇文章其实已经写过这个了,里面也写了关注的数据放在Redis中,这里就不再赘述。

然后写service层。

@Service
public class FollowService implements CommunityConstant {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    public void follow(int userId, int entityType, int entityId) {
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);
                String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);

                operations.multi();

                operations.opsForZSet().add(followeeKey, entityId, System.currentTimeMillis());
                operations.opsForZSet().add(followerKey, userId, System.currentTimeMillis());

                return operations.exec();
            }
        });
    }

    public void unfollow(int userId, int entityType, int entityId) {
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);
                String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);

                operations.multi();

                operations.opsForZSet().remove(followeeKey, entityId);
                operations.opsForZSet().remove(followerKey, userId);

                return operations.exec();
            }
        });
    }

    // 查询关注的实体的数量
    public long findFolloweeCount(int userId, int entityType) {
        String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);
        return redisTemplate.opsForZSet().zCard(followeeKey);
    }

    // 查询实体的粉丝的数量
    public long findFollowerCount(int entityType, int entityId) {
        String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);
        return redisTemplate.opsForZSet().zCard(followerKey);
    }

    // 查询当前用户是否已关注该实体
    public boolean hasFollowed(int userId, int entityType, int entityId) {
        String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);
        return redisTemplate.opsForZSet().score(followeeKey, entityId) != null;
    }

    // 查询某用户关注的人
    public List<Map<String, Object>> findFollowees(int userId, int offset, int limit) {
        String followeeKey = RedisKeyUtil.getFolloweeKey(userId, ENTITY_TYPE_USER);
        Set<Integer> targetIds = redisTemplate.opsForZSet().reverseRange(followeeKey, offset, offset + limit - 1);

        if (targetIds == null) {
            return null;
        }

        List<Map<String, Object>> list = new ArrayList<>();
        for (Integer targetId : targetIds) {
            Map<String, Object> map = new HashMap<>();
            User user = userService.findUserById(targetId);
            map.put("user", user);
            Double score = redisTemplate.opsForZSet().score(followeeKey, targetId);
            map.put("followTime", new Date(score.longValue()));
            list.add(map);
        }

        return list;
    }

    // 查询某用户的粉丝
    public List<Map<String, Object>> findFollowers(int userId, int offset, int limit) {
        String followerKey = RedisKeyUtil.getFollowerKey(ENTITY_TYPE_USER, userId);
        Set<Integer> targetIds = redisTemplate.opsForZSet().reverseRange(followerKey, offset, offset + limit - 1);

        if (targetIds == null) {
            return null;
        }

        List<Map<String, Object>> list = new ArrayList<>();
        for (Integer targetId : targetIds) {
            Map<String, Object> map = new HashMap<>();
            User user = userService.findUserById(targetId);
            map.put("user", user);
            Double score = redisTemplate.opsForZSet().score(followerKey, targetId);
            map.put("followTime", new Date(score.longValue()));
            list.add(map);
        }

        return list;
    }

}

这段代码是一个名为FollowService的服务类,用于处理关注相关的操作。它通过注入RedisTemplateUserService来处理关注逻辑和用户信息的获取。

该服务类提供了一系列方法来处理关注操作,包括关注用户、取消关注、查询关注数量、查询粉丝数量、查询是否已关注、查询关注的用户列表和查询粉丝列表等功能。

在关注和取消关注的方法中,通过使用SessionCallbackmulti()方法,实现了将多个Redis操作放入一个事务中,保证了操作的原子性。

在查询关注的用户列表和粉丝列表的方法中,通过使用opsForZSet().reverseRange()方法,从Redis的有序集合中按照分数逆序查询指定范围的元素,并将结果封装成Map对象,包含用户信息和关注时间。

整个服务类通过使用RedisTemplate提供的方法,操作Redis中的数据,实现了关注功能的存储和查询。

该服务类的设计使得关注模块的操作实现了高效、可靠和可扩展的特性,同时通过依赖注入的方式,提高了代码的灵活性和可维护性。

最后写controller层。

@Controller
public class FollowController implements CommunityConstant {

    @Autowired
    private FollowService followService;

    @Autowired
    private HostHolder hostHolder;

    @Autowired
    private UserService userService;

    @Autowired
    private EventProducer eventProducer;

    @RequestMapping(path = "/follow", method = RequestMethod.POST)
    @ResponseBody
    public String follow(int entityType, int entityId) {
        User user = hostHolder.getUser();

        followService.follow(user.getId(), entityType, entityId);

        // 触发关注事件
        Event event = new Event()
                .setTopic(TOPIC_FOLLOW)
                .setUserId(hostHolder.getUser().getId())
                .setEntityType(entityType)
                .setEntityId(entityId)
                .setEntityUserId(entityId);
        eventProducer.fireEvent(event);

        return CommunityUtil.getJSONString(0, "已关注!");
    }

    @RequestMapping(path = "/unfollow", method = RequestMethod.POST)
    @ResponseBody
    public String unfollow(int entityType, int entityId) {
        User user = hostHolder.getUser();

        followService.unfollow(user.getId(), entityType, entityId);

        return CommunityUtil.getJSONString(0, "已取消关注!");
    }

    @RequestMapping(path = "/followees/{userId}", method = RequestMethod.GET)
    public String getFollowees(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }
        model.addAttribute("user", user);

        page.setLimit(5);
        page.setPath("/followees/" + userId);
        page.setRows((int) followService.findFolloweeCount(userId, ENTITY_TYPE_USER));

        List<Map<String, Object>> userList = followService.findFollowees(userId, page.getOffset(), page.getLimit());
        if (userList != null) {
            for (Map<String, Object> map : userList) {
                User u = (User) map.get("user");
                map.put("hasFollowed", hasFollowed(u.getId()));
            }
        }
        model.addAttribute("users", userList);

        return "/site/followee";
    }

    @RequestMapping(path = "/followers/{userId}", method = RequestMethod.GET)
    public String getFollowers(@PathVariable("userId") int userId, Page page, Model model) {
        User user = userService.findUserById(userId);
        if (user == null) {
            throw new RuntimeException("该用户不存在!");
        }
        model.addAttribute("user", user);

        page.setLimit(5);
        page.setPath("/followers/" + userId);
        page.setRows((int) followService.findFollowerCount(ENTITY_TYPE_USER, userId));

        List<Map<String, Object>> userList = followService.findFollowers(userId, page.getOffset(), page.getLimit());
        if (userList != null) {
            for (Map<String, Object> map : userList) {
                User u = (User) map.get("user");
                map.put("hasFollowed", hasFollowed(u.getId()));
            }
        }
        model.addAttribute("users", userList);

        return "/site/follower";
    }

    private boolean hasFollowed(int userId) {
        if (hostHolder.getUser() == null) {
            return false;
        }

        return followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);
    }

}

上面这段代码是一个名为FollowController的控制器类,用于处理关注相关的请求。它通过注入FollowServiceUserServiceHostHolderEventProducer来实现关注功能和获取用户信息。

该控制器类提供了关注和取消关注的请求处理方法,其中:

  • follow()方法用于处理关注请求。它获取当前登录用户信息,调用followServicefollow()方法进行关注操作,并触发关注事件。
  • unfollow()方法用于处理取消关注请求。它获取当前登录用户信息,调用followServiceunfollow()方法进行取消关注操作。
  • getFollowees()方法用于获取用户关注的人列表。它根据用户ID获取用户信息,设置分页信息,调用followServicefindFollowees()方法获取关注的人列表,并将结果封装到模型中。
  • getFollowers()方法用于获取用户的粉丝列表。它根据用户ID获取用户信息,设置分页信息,调用followServicefindFollowers()方法获取粉丝列表,并将结果封装到模型中。

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.coloradmin.cn/o/1490674.html

如若内容造成侵权/违法违规/事实不符,请联系多彩编程网进行投诉反馈,一经查实,立即删除!

相关文章

哈希的简单介绍

unordered系列关联式容器 在C98中&#xff0c;STL提供了底层为红黑树结构的一系列关联式容器&#xff0c;在查询时效率可达到 l o g 2 N log_2 N log2​N&#xff0c;即最差情况下需要比较红黑树的高度次&#xff0c;当树中的节点非常多时&#xff0c;查询效率也不理想。最好的…

少儿编程 中国电子学会C++等级考试一级历年真题答案解析【持续更新 已更新82题】

C 等级考试一级考纲说明 一、能力目标 通过本级考核的学生&#xff0c;能对 C 语言有基本的了解&#xff0c;会使用顺序结构、选择结构、循环结构编写程序&#xff0c;具体用计算思维的方式解决简单的问题。 二、考核目标 考核内容是根据软件开发所需要的技能和知识&#x…

深度学习_18_模型的下载与读取

在深度学习的过程中&#xff0c;需要将训练好的模型运用到我们要使用的另一个程序中&#xff0c;这就需要模型的下载与转移操作 代码&#xff1a; import math import torch from torch import nn from d2l import torch as d2l import matplotlib.pyplot as plt# 生成随机的…

私有化部署自己的ChatGPT,免费开源的chatgpt-next-web搭建

随着AI的应用变广&#xff0c;各类AI程序已逐渐普及&#xff0c;尤其是在一些日常办公、学习等与撰写/翻译文稿密切相关的场景&#xff0c;大家都希望找到一个适合自己的稳定可靠的ChatGPT软件来使用。 ChatGPT-Next-Web就是一个很好的选择。它是一个Github上超人气的免费开源…

新零售SaaS架构:订单履约系统的概念模型设计

订单履约系统的概念模型 订单&#xff1a;客户提交购物请求后&#xff0c;生成的买卖合同&#xff0c;通常包含客户信息、下单日期、所购买的商品或服务明细、价格、数量、收货地址以及支付方式等详细信息。 子订单&#xff1a;为了更高效地进行履约&#xff0c;大订单可能会被…

安卓开发:计时器

一、新建模块 二、填写应用名称和模块名称 三、选择模块&#xff0c;Next 四、可以保持不变&#xff0c;Finish 五、相关目录文件 六、相关知识 七、&#xff1f;

正大国际:期货结算价是如何理解呢?结算价有什么作用?

如何理解期货结算价&#xff1a; 什么是商品期货当日结算价&#xff0c; 商品期货当日结算价是指某一期货合约当日交易期间成交价格按成交量的加权平均价。当日 无成交的&#xff0c;当日结算价按照交易所相关规定确定。 股指期货当日结算价是指某一期货合约当日交易期间最后一…

采购软件是如何改善采购周期?

采购是一个复杂的职能重叠网络&#xff0c;由市场分析、供应商选择、发布 RPF/RFQ、合同谈判等多个工作流程组成。此外&#xff0c;时间紧迫、满足客户期望等压力也使这项工作极具挑战性。因此&#xff0c;如果企业在采购过程中采取短视的方法&#xff0c;没有遵循适当的结构&a…

Pygame教程02:图片的加载+缩放+旋转+显示操作

------------★Pygame系列教程★------------ Pygame教程01&#xff1a;初识pygame游戏模块 Pygame教程02&#xff1a;图片的加载缩放旋转显示操作 Pygame教程03&#xff1a;文本显示字体加载transform方法 Pygame教程04&#xff1a;draw方法绘制矩形、多边形、圆、椭圆、弧…

海王星(Neptune)系列和大禹(DAYU)系列OpenHarmony智能硬件配置解决方案

海王星&#xff08;Neptune&#xff09;系列和大禹&#xff08;DAYU&#xff09;系列OpenHarmony智能硬件对OS的适配、部件拼装配置、启动配置和文件系统配置等。产品解决方案的源码路径规则为&#xff1a;vendor/{产品解决方案厂商}/{产品名称}_。 解决方案的目录树规则如下&…

React__ 二、React状态管理工具Redux的使用

提示&#xff1a;文章写完后&#xff0c;目录可以自动生成&#xff0c;如何生成可参考右边的帮助文档 文章目录 前言redux状态管理安装redux创建文件 并使用传参action 总结 前言 redux状态管理插件的使用 提示&#xff1a;以下是本篇文章正文内容&#xff0c;下面案例可供参考…

Typescript 哲学 morn on funtion

函数重载 overload 有一些编程语言&#xff08;eg&#xff1a;java&#xff09;允许不同的函数参数&#xff0c;对应不同的函数实现。但是&#xff0c;JavaScript 函数只能有一个实现&#xff0c;必须在这个实现当中&#xff0c;处理不同的参数。因此&#xff0c;函数体内部就…

【系统需求分析报告-项目案例直接套用】

软件需求分析报告 软件开发要求项目建设内容物理设计安全系统设计安全网络安全设计应用安全设计用户安全管理性能设计稳定性设计安全性设计兼容性设计易操作性设计可维护行设计 软件开发全套精华资料过去进主页领取。

10亿数据如何快速插入MySQL

最快的速度把10亿条数据导入到数据库,首先需要和面试官明确一下,10亿条数据什么形式存在哪里,每条数据多大,是否有序导入,是否不能重复,数据库是否是MySQL? 有如下约束 10亿条数据,每条数据 1 Kb 数据内容是非结构化的用户访问日志,需要解析后写入到数据库 数据存放在…

2024新版SonarQube+JenKins+Github联动代码扫描(2)-SonarQube代码扫描

文章目录 前言一、docker方式安装sonar二、启动容器三、创建数据库四、启动sonarqube五、访问sonar六、如果访问报错-通过sonar日志定位问题七、修改密码八、汉化&#xff08;看个人选择&#xff09;九、扫描十、我遇到的Sonar报错以及解决办法 总结 前言 这是2024新版SonarQu…

【OpenGL编程手册08】 摄像机

一、说明 前面的教程中我们讨论了观察矩阵以及如何使用观察矩阵移动场景&#xff08;我们向后移动了一点&#xff09;。OpenGL本身没有摄像机(Camera)的概念&#xff0c;但我们可以通过把场景中的所有物体往相反方向移动的方式来模拟出摄像机&#xff0c;产生一种我们在移动的感…

关于python函数参数传递

参数传递 在 python 中&#xff0c;类型属于对象&#xff0c;对象有不同类型的区分&#xff0c;变量是没有类型的&#xff1a; 在下面的代码示例重&#xff0c;[1,2,3] 是 List 类型&#xff0c;“qayrup” 是 String 类型&#xff0c;而变量 a 是没有类型&#xff0c;它仅仅…

PyTorch深度学习实战(38)——StyleGAN详解与实现

PyTorch深度学习实战&#xff08;38&#xff09;——StyleGAN详解与实现 0. 前言1. StyleGAN1.1 模型介绍1.2 模型策略分析 2. 实现 StyleGAN2.1 生成图像2.2 风格迁移 小结系列链接 0. 前言 StyleGAN (Style-Generative Adversarial Networks) 是生成对抗网络 (Generative Ad…

使用AI创建令人惊叹的3D模型

老子云平台《《《《《 使内容创作者能够在一分钟内毫不费力地将文本和图像转换为引人入胜的 3D 资产。 文本转 3D 我们的文本转 3D 工具使创作者&#xff08;包括那些没有 3D 经验的创作者&#xff09;能够使用文本输入在短短一分钟内生成 3D 模型。 一句话生成3D模型 老子…

Day31|贪心算法1

贪心的本质是选择每一阶段的局部最优&#xff0c;从而达到全局最优。 无固定套路&#xff0c;举不出反例&#xff0c;就可以试试贪心。 一般解题步骤&#xff1a; 1.将问题分解成若干子问题 2.找出适合的贪心策略 3.求解每一个子问题的最优解 4.将局部最优解堆叠成全局最…