仿牛客网项目---点赞模块的实现

2024-03-05 13:52

本文主要是介绍仿牛客网项目---点赞模块的实现,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!

本篇文章介绍一下项目中的点赞模块。

点赞模块是一个通过使用Redis实现的功能模块,它提供了点赞操作的处理逻辑和数据存取功能。通过服务类和控制器类的配合,点赞模块实现了用户对实体的点赞、点赞数量的查询、点赞状态的查询等功能。该模块使用了Redis作为数据存储,通过Redis的事务支持和数据结构操作,实现了点赞操作的原子性和高效性。同时,通过依赖注入和控制反转的思想,实现了代码的解耦和灵活性,使得点赞模块具有良好的可维护性和可扩展性。

首先我们写一个RedisKeyUtil的工具类,这个工具类提供了一些用于在Redis中生成键的方法。

public class RedisKeyUtil {// 某个实体的赞// like:entity:entityType:entityId -> set(userId)public static String getEntityLikeKey(int entityType, int entityId) {return PREFIX_ENTITY_LIKE + SPLIT + entityType + SPLIT + entityId;}// 某个用户的赞// like:user:userId -> intpublic static String getUserLikeKey(int userId) {return PREFIX_USER_LIKE + SPLIT + userId;}// 某个用户关注的实体// followee:userId:entityType -> zset(entityId,now)public static String getFolloweeKey(int userId, int entityType) {return PREFIX_FOLLOWEE + SPLIT + userId + SPLIT + entityType;}// 某个实体拥有的粉丝// follower:entityType:entityId -> zset(userId,now)public static String getFollowerKey(int entityType, int entityId) {return PREFIX_FOLLOWER + SPLIT + entityType + SPLIT + entityId;}// 登录验证码public static String getKaptchaKey(String owner) {return PREFIX_KAPTCHA + SPLIT + owner;}// 登录的凭证public static String getTicketKey(String ticket) {return PREFIX_TICKET + SPLIT + ticket;}// 用户public static String getUserKey(int userId) {return PREFIX_USER + SPLIT + userId;}// 单日UVpublic static String getUVKey(String date) {return PREFIX_UV + SPLIT + date;}// 区间UVpublic static String getUVKey(String startDate, String endDate) {return PREFIX_UV + SPLIT + startDate + SPLIT + endDate;}// 单日活跃用户public static String getDAUKey(String date) {return PREFIX_DAU + SPLIT + date;}// 区间活跃用户public static String getDAUKey(String startDate, String endDate) {return PREFIX_DAU + SPLIT + startDate + SPLIT + endDate;}// 帖子分数public static String getPostScoreKey() {return PREFIX_POST + SPLIT + "score";}}

举例来说,通过使用getEntityLikeKey方法,可以生成一个用于存储特定实体点赞记录的键,通过使用getUserLikeKey方法,可以生成一个用于存储特定用户点赞记录的键。其他方法则可以生成用于存储用户数据、关注关系、验证码、登录凭证等的键。

看到这里,你应该会觉得很奇怪,为什么没有DAO层呢?

因为点赞数据的存储和查询需求可以完全由Redis满足,并且Redis作为一个高性能的内存数据库能够提供快速的读写操作,简化了数据访问的复杂性和开销,同时满足了性能要求。此外,点赞数据可能具有相对简单的数据结构,可以直接使用Redis的数据结构进行存储和查询,而不需要传统的数据库访问层。

所以说DAO层在这个项目就没有用到了,我这个项目的点赞模块用的是Redis,关于一些点赞的信息我是用redis来存的。

然后再来写LikeService文件,即service层。

@Service
public class LikeService {@Autowiredprivate RedisTemplate redisTemplate;// 点赞public void like(int userId, int entityType, int entityId, int entityUserId) {redisTemplate.execute(new SessionCallback() {@Overridepublic Object execute(RedisOperations operations) throws DataAccessException {String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);boolean isMember = operations.opsForSet().isMember(entityLikeKey, userId);operations.multi();if (isMember) {operations.opsForSet().remove(entityLikeKey, userId);operations.opsForValue().decrement(userLikeKey);} else {operations.opsForSet().add(entityLikeKey, userId);operations.opsForValue().increment(userLikeKey);}return operations.exec();}});}// 查询某实体点赞的数量public long findEntityLikeCount(int entityType, int entityId) {String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);return redisTemplate.opsForSet().size(entityLikeKey);}// 查询某人对某实体的点赞状态public int findEntityLikeStatus(int userId, int entityType, int entityId) {String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);return redisTemplate.opsForSet().isMember(entityLikeKey, userId) ? 1 : 0;}// 查询某个用户获得的赞public int findUserLikeCount(int userId) {String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);return count == null ? 0 : count.intValue();}}
  1. like(int userId, int entityType, int entityId, int entityUserId):点赞方法,用于给特定实体点赞。它首先生成实体点赞的键和用户点赞的键,然后通过Redis的事务支持(multi()exec()方法)来保证点赞操作的原子性。根据用户是否已经点赞,执行相应的操作(添加或移除点赞),并更新用户点赞数。

  2. findEntityLikeCount(int entityType, int entityId):查询某实体的点赞数量。它使用RedisKeyUtil生成实体点赞的键,并通过Redis的opsForSet().size()方法获取集合的大小,即点赞数量。

  3. findEntityLikeStatus(int userId, int entityType, int entityId):查询某人对某实体的点赞状态。它使用RedisKeyUtil生成实体点赞的键,并通过Redis的opsForSet().isMember()方法判断用户是否已经点赞。

  4. findUserLikeCount(int userId):查询某个用户获得的赞数量。它使用RedisKeyUtil生成用户点赞的键,并通过Redis的opsForValue().get()方法获取用户点赞数。

最后写controller层,即LikeController。

@Controller
public class LikeController implements CommunityConstant {//省略了注入LikeService、HostHolder、EventProducer和RedisTemplate来处理点赞逻辑的代码@RequestMapping(path = "/like", method = RequestMethod.POST)@ResponseBodypublic String like(int entityType, int entityId, int entityUserId, int postId) {User user = hostHolder.getUser();// 点赞likeService.like(user.getId(), entityType, entityId, entityUserId);// 数量long likeCount = likeService.findEntityLikeCount(entityType, entityId);// 状态int likeStatus = likeService.findEntityLikeStatus(user.getId(), entityType, entityId);// 返回的结果Map<String, Object> map = new HashMap<>();map.put("likeCount", likeCount);map.put("likeStatus", likeStatus);// 触发点赞事件if (likeStatus == 1) {Event event = new Event().setTopic(TOPIC_LIKE).setUserId(hostHolder.getUser().getId()).setEntityType(entityType).setEntityId(entityId).setEntityUserId(entityUserId).setData("postId", postId);eventProducer.fireEvent(event);}if(entityType == ENTITY_TYPE_POST) {// 计算帖子分数String redisKey = RedisKeyUtil.getPostScoreKey();redisTemplate.opsForSet().add(redisKey, postId);}return CommunityUtil.getJSONString(0, null, map);}}

上面这段代码是一个名为LikeController的控制器类,用于处理点赞相关的请求。它通过注入LikeServiceHostHolderEventProducerRedisTemplate来处理点赞逻辑。

控制器中的主要方法是like()方法,用于处理点赞请求。该方法接受实体类型、实体ID、实体创建者ID和帖子ID作为参数。在方法中,首先获取当前用户信息,然后调用likeService的点赞方法,对实体进行点赞操作。

接下来,通过调用likeService的方法获取点赞数量和点赞状态,并将结果存储在一个Map对象中。然后,根据点赞状态触发相应的点赞事件,创建一个Event对象,并通过eventProducer发送事件。

如果实体类型是帖子(ENTITY_TYPE_POST),则计算帖子的分数并存储到Redis中。

最后,通过CommunityUtil.getJSONString()方法将结果封装成JSON字符串并返回给前端。

控制器类通过调用likeService处理点赞逻辑,而不是使用DAO层进行数据访问。这是因为点赞操作的数据存储和查询可以完全由Redis满足,并且通过调用likeService提供的方法,可以直接在控制器中处理点赞逻辑,避免了引入额外的DAO层。

这篇关于仿牛客网项目---点赞模块的实现的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!



http://www.chinasem.cn/article/776726

相关文章

分布式锁在Spring Boot应用中的实现过程

《分布式锁在SpringBoot应用中的实现过程》文章介绍在SpringBoot中通过自定义Lock注解、LockAspect切面和RedisLockUtils工具类实现分布式锁,确保多实例并发操作... 目录Lock注解LockASPect切面RedisLockUtils工具类总结在现代微服务架构中,分布

Java使用Thumbnailator库实现图片处理与压缩功能

《Java使用Thumbnailator库实现图片处理与压缩功能》Thumbnailator是高性能Java图像处理库,支持缩放、旋转、水印添加、裁剪及格式转换,提供易用API和性能优化,适合Web应... 目录1. 图片处理库Thumbnailator介绍2. 基本和指定大小图片缩放功能2.1 图片缩放的

精选20个好玩又实用的的Python实战项目(有图文代码)

《精选20个好玩又实用的的Python实战项目(有图文代码)》文章介绍了20个实用Python项目,涵盖游戏开发、工具应用、图像处理、机器学习等,使用Tkinter、PIL、OpenCV、Kivy等库... 目录① 猜字游戏② 闹钟③ 骰子模拟器④ 二维码⑤ 语言检测⑥ 加密和解密⑦ URL缩短⑧ 音乐播放

Python使用Tenacity一行代码实现自动重试详解

《Python使用Tenacity一行代码实现自动重试详解》tenacity是一个专为Python设计的通用重试库,它的核心理念就是用简单、清晰的方式,为任何可能失败的操作添加重试能力,下面我们就来看... 目录一切始于一个简单的 API 调用Tenacity 入门:一行代码实现优雅重试精细控制:让重试按我

Springboot项目启动失败提示找不到dao类的解决

《Springboot项目启动失败提示找不到dao类的解决》SpringBoot启动失败,因ProductServiceImpl未正确注入ProductDao,原因:Dao未注册为Bean,解决:在启... 目录错误描述原因解决方法总结***************************APPLICA编

Redis客户端连接机制的实现方案

《Redis客户端连接机制的实现方案》本文主要介绍了Redis客户端连接机制的实现方案,包括事件驱动模型、非阻塞I/O处理、连接池应用及配置优化,具有一定的参考价值,感兴趣的可以了解一下... 目录1. Redis连接模型概述2. 连接建立过程详解2.1 连php接初始化流程2.2 关键配置参数3. 最大连

Python实现网格交易策略的过程

《Python实现网格交易策略的过程》本文讲解Python网格交易策略,利用ccxt获取加密货币数据及backtrader回测,通过设定网格节点,低买高卖获利,适合震荡行情,下面跟我一起看看我们的第一... 网格交易是一种经典的量化交易策略,其核心思想是在价格上下预设多个“网格”,当价格触发特定网格时执行买

python设置环境变量路径实现过程

《python设置环境变量路径实现过程》本文介绍设置Python路径的多种方法:临时设置(Windows用`set`,Linux/macOS用`export`)、永久设置(系统属性或shell配置文件... 目录设置python路径的方法临时设置环境变量(适用于当前会话)永久设置环境变量(Windows系统

Python对接支付宝支付之使用AliPay实现的详细操作指南

《Python对接支付宝支付之使用AliPay实现的详细操作指南》支付宝没有提供PythonSDK,但是强大的github就有提供python-alipay-sdk,封装里很多复杂操作,使用这个我们就... 目录一、引言二、准备工作2.1 支付宝开放平台入驻与应用创建2.2 密钥生成与配置2.3 安装ali

Spring Security 单点登录与自动登录机制的实现原理

《SpringSecurity单点登录与自动登录机制的实现原理》本文探讨SpringSecurity实现单点登录(SSO)与自动登录机制,涵盖JWT跨系统认证、RememberMe持久化Token... 目录一、核心概念解析1.1 单点登录(SSO)1.2 自动登录(Remember Me)二、代码分析三、