(黑马点评) 五、探店达人系列功能实现

ops/2024/9/20 4:20:13/ 标签: redis, 学习, 黑马点评

5.1 发布和查看探店笔记

5.1.1 发布探店笔记

        这块代码黑马已经完成了,在发布探店笔记界面,有两块内容是需要上传的。一是笔记内容,二是笔记配图。其中笔记配图部分黑马使用的是上传到本地前端服务器上面的。我我觉得可以将图片文件发布在阿里云的OSS存储也行,该功能等后续会完成。等黑马点评后端部分完成后、再去分析黑马写的前端代码。然后再将该功能实现。

文件上传功能实现

在系统常量中修改文件上传的地址(改成你自己的)

// 图片上传路径public static final String IMAGE_UPLOAD_DIR = "D:\\software\\hm-dianping-nginx\\nginx-1.18.0\\html\\hmdp\\imgs";
@Slf4j
@RestController
@RequestMapping("upload")
public class UploadController {@PostMapping("blog")public Result uploadImage(@RequestParam("file") MultipartFile image) {try {// 获取原始文件名称String originalFilename = image.getOriginalFilename();// 生成新文件名String fileName = createNewFileName(originalFilename);// 保存文件image.transferTo(new File(SystemConstants.IMAGE_UPLOAD_DIR, fileName));// 返回结果log.debug("文件上传成功,{}", fileName);return Result.ok(fileName);} catch (IOException e) {throw new RuntimeException("文件上传失败", e);}}private String createNewFileName(String originalFilename) {// 获取后缀String suffix = StrUtil.subAfter(originalFilename, ".", true);// 生成目录String name = UUID.randomUUID().toString();int hash = name.hashCode();int d1 = hash & 0xF;int d2 = (hash >> 4) & 0xF;// 判断目录是否存在File dir = new File(SystemConstants.IMAGE_UPLOAD_DIR, StrUtil.format("/blogs/{}/{}", d1, d2));if (!dir.exists()) {dir.mkdirs();}// 生成文件名return StrUtil.format("/blogs/{}/{}/{}.{}", d1, d2, name, suffix);}
笔记发布功能实现 
    @PostMappingpublic Result saveBlog(@RequestBody Blog blog) {// 获取登录用户UserDTO user = UserHolder.getUser();blog.setUserId(user.getId());// 保存探店博文blogService.save(blog);// 返回idreturn Result.ok(blog.getId());}
发布功能测试

5.1.2 查看探店笔记

        添加TableField注解表示这三个字段不是数据库中的字段。我们查看探店笔记时,需要将创作者的信息也显示出来,但是又不能显示过多暴露,只需要有头像、姓名之类的就好了。

/*** 用户图标*/@TableField(exist = false)private String icon;/*** 用户姓名*/@TableField(exist = false)private String name;
查看探店笔记代码实现
/*** 根据id查询探店笔记* @param id* @return*/@GetMapping("/{id}")public Result queryBlogById(@PathVariable("id") Long id) {return blogService.queryBlogById(id);}/*** 根据id查博客笔记* @param id* @return*/@Overridepublic Result queryBlogById(Long id) {//1. 查询blogBlog blog = getById(id);if(blog==null){return Result.fail("博客不存在");}//2.查用户queryBlogUser(blog);return Result.ok(blog);}/*** 复用方法封装* @param blog*/private void queryBlogUser(Blog blog){Long userId = blog.getUserId();User user = userService.getById(userId);blog.setName(user.getNickName());blog.setIcon(user.getIcon());}
查看功能测试

5.2 点赞功能实现

5.2.1 当前点赞功能存在的问题

不校验点赞用户信息,一个人可以无限刷赞

    /*** 修改点赞数量* @param id* @return*/@PutMapping("/like/{id}")public Result likeBlog(@PathVariable("id") Long id) {// 修改点赞数量// update tb_blog set liked liked + 1 where id = #{id}blogService.update().setSql("liked = liked + 1").eq("id", id).update();return Result.ok();}

5.2.2 完善点赞功能需求与实现步骤

需求:

1. 同一用户只能点赞一次,再次点击即取消点赞

2. 如果当前用户已经点赞,则点赞按钮高亮显示(isLike 告知前端即可) 

步骤:

1. 给Blog类添加一个isList字段,标记当前用户是否点赞

2. 修改点赞功能,利用Redis的set集合特性存储当前笔记的点赞用户id,用于判断该用户是否给笔记点过赞,为点过则赞 +1 ,否则赞-1

3. 在根据id查询Blog业务时,就判断当前登录用户有无点赞记录,赋值给isList字段.

4. 在分页查询Blog业务时,也去判断并赋值

5.2.3 点赞功能实现

添加一个isList字段

    /*** 是否点赞过了*/@TableField(exist = false)private Boolean isLike;

修改点赞功能

/*** 点赞* @param id* @return*/@Overridepublic Result likeBlog(Long id) {//1.判断当前用户有没点赞Long userId = UserHolder.getUser().getId();String key = RedisConstants.BLOG_LIKED_KEY + id;Boolean isMember =  stringRedisTemplate.opsForSet().isMember(key,userId.toString());if(BooleanUtil.isFalse(isMember)){//2.更新数据库信息 点赞+1boolean isSuccess =  update().setSql("liked = liked + 1").eq("id",id).update();//3. 保存用户到Redis的set集合if(isSuccess){stringRedisTemplate.opsForSet().add(key,userId.toString());}}else{//4. 点赞-1boolean isSuccess =  update().setSql("liked = liked - 1").eq("id",id).update();//5。 移除Redisif(isSuccess){stringRedisTemplate.opsForSet().remove(key,userId.toString());}}return Result.ok();}

添加判断功能

    /*** 查询点赞状态* @param blog*/private void isBlogLiked(Blog blog) {Long userId = UserHolder.getUser().getId();String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();Boolean isMember =  stringRedisTemplate.opsForSet().isMember(key,userId.toString());blog.setIsLike(BooleanUtil.isTrue(isMember));}/*** 查多个* @param current* @return*/@Overridepublic Result queryHotBlog(Integer current) {//    根据用户查询Page<Blog> page = query().orderByDesc("liked").page(new Page<>(current, SystemConstants.MAX_PAGE_SIZE));// 获取当前页数据List<Blog> records = page.getRecords();// 查询用户records.forEach(blog -> {this.queryBlogUser(blog);// 查询点赞状态this.isBlogLiked(blog);});return Result.ok(records);}/*** 根据id查博客笔记* @param id* @return*/@Overridepublic Result queryBlogById(Long id) {//1. 查询blogBlog blog = getById(id);if(blog==null){return Result.fail("博客不存在");}//2.查用户queryBlogUser(blog);//3. 查询点赞状态isBlogLiked(blog);return Result.ok(blog);}

5.2.4 点赞功能测试

5.3 点赞排行榜功能实现

5.3.1 数据结构选型说明

需求是能排序且去重的排行榜功能,因此我们选用zset集合来实现这些需求

5.3.2 排行功能实现

修改点赞及点赞状态逻辑

/*** 查询点赞状态* @param blog*/private void isBlogLiked(Blog blog) {Long userId = UserHolder.getUser().getId();String key = RedisConstants.BLOG_LIKED_KEY + blog.getId();Double score =  stringRedisTemplate.opsForZSet().score(key,userId.toString());blog.setIsLike(score != null);}/*** 点赞* @param id* @return*/@Overridepublic Result likeBlog(Long id) {//1.判断当前用户有没点赞Long userId = UserHolder.getUser().getId();String key = RedisConstants.BLOG_LIKED_KEY + id;Double score =  stringRedisTemplate.opsForZSet().score(key,userId.toString());if(score == null){//2.更新数据库信息 点赞+1boolean isSuccess =  update().setSql("liked = liked + 1").eq("id",id).update();//3. 保存用户到Redis的set集合if(isSuccess){stringRedisTemplate.opsForZSet().add(key,userId.toString(),System.currentTimeMillis());}}else{//4. 点赞-1boolean isSuccess =  update().setSql("liked = liked - 1").eq("id",id).update();//5。 移除Redisif(isSuccess){stringRedisTemplate.opsForZSet().remove(key,userId.toString());}}return Result.ok();}

实现排行榜功能

ZRANGE 查询范围内的元素

/*** 查询点赞排行榜* @param id* @return*/@Overridepublic Result queryBlogLikes(Long id) {// 使用zrange查询TOP5Set<String> top5StrIds = stringRedisTemplate.opsForZSet().range(RedisConstants.BLOG_LIKED_KEY + id, 0, 4);if(top5StrIds==null || top5StrIds.isEmpty()){return Result.ok(Collections.emptyList());}List<Long> ids = top5StrIds.stream().map(Long::valueOf).collect(Collectors.toList());// 根据用户id查询数据库List<User> users = userService.listByIds(ids);// DTOList<UserDTO> userDTOList = users.stream().map(user -> BeanUtil.copyProperties(user, UserDTO.class)).collect(Collectors.toList());return Result.ok(userDTOList);}

5.3.3 排行功能测试

优化

发现查询点赞排行榜的顺序不正确——原因:数据库in使用时,无法保障顺序

添加ORDER BY FIELD 自定义顺序
 

 // 根据用户id查询数据库// 自定义sql查询List<User> users = userService.query().in("id", ids).last("ORDER BY FIELD(id," + StrUtil.join(",", ids) + ")").list();

  

5.4 查看用户笔记列表功能实现

在点击用户头像进入首页时,可以查询该用户的博客列表进行展示

博客列表
查看博客列表

/*** 根据用户id查询探店笔记列表* @param current* @param id* @return*/@GetMapping("/of/user")public Result queryBlogByUserid(@RequestParam(value = "current",defaultValue = "1") Integer current,@RequestParam("id") Long id) {// 根据用户查询Page<Blog> page = blogService.query().eq("user_id", id).page(new Page<>(current,SystemConstants.MAX_PAGE_SIZE));// 获取当前页数据List<Blog> records = page.getRecords();return Result.ok(records);}


http://www.ppmy.cn/ops/113252.html

相关文章

随笔十一、wsl子系统ubuntu磁盘清理

基于wsl工具的ubuntu虚拟磁盘在编译SDK使用一段时间后&#xff0c;就膨胀得很大&#xff0c;需要瘦身一下 1. ubuntu子系统内释放空间 检查用户空间使用情况 du -hc --max-depth1 ~ | sort -rh 可以看到cache占用了11G空间&#xff0c;删除下 rm -rf ~/.cache/* rm -rf /tmp/*…

libwebsockets之日志系统

libwebsockets日志系统也是分等级的&#xff0c;如下: #define LLL_ERR (1 << 0)#define LLL_WARN (1 << 1)#define LLL_NOTICE (1 << 2)#define LLL_INFO (1 << 3)#define LLL_DEBUG (1 << 4)#define LLL_PARSER (1 << 5)#…

基于SpringBoot+Vue的企业会议室预定管理系统

作者&#xff1a;计算机学姐 开发技术&#xff1a;SpringBoot、SSM、Vue、MySQL、JSP、ElementUI、Python、小程序等&#xff0c;“文末源码”。 专栏推荐&#xff1a;前后端分离项目源码、SpringBoot项目源码、SSM项目源码 系统展示 【2025最新】基于JavaSpringBootVueMySQL的…

【Hot100】LeetCode—4. 寻找两个正序数组的中位数

目录 1- 思路题目识别二分 2- 实现⭐4. 寻找两个正序数组的中位数——题解思路 3- ACM 实现 原题链接&#xff1a;4. 寻找两个正序数组的中位数 1- 思路 题目识别 识别1 &#xff1a;给定两个数组 nums1 和 nums2 &#xff0c;找出数组的中位数 二分 思路 将寻找中位数 —…

MinIO【部署 02】Linux集群版本及Windows单机版、单机多目录版、分布式版(cmd启动脚本及winsw脚本分享)

Linux集群版及Windows单机版分布式版 1.Linux集群版1.1 安装启动停止1.2 将MinIO添加到服务 2.Windows2.1 官网安装2.2 本地测试2.2.1 cmd启动脚本2.2.2 winsw脚本 3.总结 1.Linux集群版 官网下载地址 https://min.io/download#/linux&#xff1b; 官网安装文档 https://min.i…

SpringCloud的学习(二),Consul服务注册与发现、分布式配置,以及 服务调用和负载均衡

介绍 Consul 是一套开源的分布式服务发现和配置管理系统&#xff0c;由 HashiCorp 公司用 Go 语言开发。 提供了微服务系统中的服务治理、配置中心、控制总线等功能。这些功能中的每一个都可以根据需要单独使用&#xff0c;也可以一起使用以构建全方位的服务网格&#xff0c;…

计算机毕业设计 扶贫助农系统的设计与实现 Java实战项目 附源码+文档+视频讲解

博主介绍&#xff1a;✌从事软件开发10年之余&#xff0c;专注于Java技术领域、Python人工智能及数据挖掘、小程序项目开发和Android项目开发等。CSDN、掘金、华为云、InfoQ、阿里云等平台优质作者✌ &#x1f345;文末获取源码联系&#x1f345; &#x1f447;&#x1f3fb; 精…

毕业论文写作会用到的AI软件!一定不能错过的18个网站!(务必收藏)

AI毕业论文写作它可以提供论文摘要、大纲、选题确立等多种写作辅助&#xff0c;还能帮助我们完成开题报告、实验报告、辩论灵感等内容。无论是文章纠正、批改&#xff0c;还是改写降重&#xff0c;它都能轻松搞定。甚至连论文致谢、创新创业计划书等都能为我们提供帮助。 以下…

【vue】vue3+ts对接科大讯飞大模型3.5智能AI

如今ai步及生活的方方面面,你是否也想在自己的网站接入ai呢&#xff1f;今天分享科大讯飞大模型3.5智能AI对接。 获取APPID、APISecret、APIKey 讯飞开放平台注册登录控制台创建自己的应用复制备用 准备工作做好,直接开始上代码了。 源码参考 <script setup lang"t…

我的demo保卫萝卜中的技术要点

管理类&#xff1a; GameManager&#xff08;单例&#xff09;&#xff0c;GameController(单例)&#xff1b; 一些其他的管理类&#xff08;PlayerManager,AudioSourceManager,FactoryManager&#xff09;作为GameManager的成员变量存在&#xff08;这样也可以保证只有一个存…

MySQL 数据库与表的创建指南

MySQL 数据库与表的创建指南 在进行 MySQL 开发时&#xff0c;了解如何创建数据库和表是基础。本文将详细介绍如何通过 MySQL 的 SQL 语句创建数据库和表&#xff0c;并解释每个步骤中的关键点。 1. 什么是 MySQL&#xff1f; MySQL 是目前最流行的开源关系型数据库管理系统…

C++——string类

1.初识string string属于C标准库&#xff0c;而不属于STL&#xff0c;STL也属于C标准库 string是管理字符的顺序表&#xff0c;用来管理字符数组 string是模板&#xff0c;只是库直接给它typedef了&#xff0c;直接实例化了 string是动态开辟的字符数组&#xff0c;指向的空间在…

Mycat搭建分库分表

分库分表解决的问题 单表数据量过大带来的性能和存储容量的限制的问题&#xff1a; 索引效率下降读写瓶颈存储容量限制事务性能问题分库分表架构 再搭建一对主从复制节点&#xff0c;3307主节点&#xff0c;3309从节点配置数据源 dw1 , dr1,创建集群c1创建逻辑库 CREATE DATAB…

图书管理系统(面向对象的编程练习)

图书管理系统&#xff08;面向对象的编程练习&#xff09; 1.系统演示2.设计框架讲解3.代码的详细讲解3.1 多本书籍的实现3.2 不同操作人员的实现3.3 不同work操作的实现 1.系统演示 下面主要展示系统的删除图书功能和显示图书功能&#xff0c;帮助大家在开始写代码前先了解图…

85-MySQL怎么判断要不要加索引

在MySQL中&#xff0c;决定是否为表中的列添加索引通常基于查询性能的考量。以下是一些常见的情况和策略&#xff1a; 查询频繁且对性能有影响的列&#xff1a;如果某个列经常用于查询条件&#xff0c;且没有创建索引&#xff0c;查询性能可能会下降。 在WHERE、JOIN和ORDER B…

AI应用开发平台Dify本地Ubuntu环境部署结合内网穿透远程管理大模型

文章目录 前言1. Docker部署Dify2. 本地访问Dify3. Ubuntu安装Cpolar4. 配置公网地址5. 远程访问6. 固定Cpolar公网地址7. 固定地址访问 前言 本文主要介绍如何在Linux Ubuntu系统使用Docker快速部署大语言模型应用开发平台Dify,并结合cpolar内网穿透工具实现公网环境远程访问…

系统 IO

"裸奔"层次&#xff1a;不带操作系统的编程 APP(应用程序) -------------------------------- Hardware(硬件) 特点&#xff1a;简单&#xff0c;应用程序直接操作硬件(寄存器) 缺点&#xff1a; 1. 搞应用开发的必须要了解硬件的实现细节&#xff0c;能够看懂原理图…

【数据结构】十大经典排序算法总结与分析

文章目录 前言1. 十大经典排序算法分类2. 相关概念3. 十大经典算法总结4. 补充内容4.1 比较排序和非比较排序的区别4.2 稳定的算法就真的稳定了吗&#xff1f;4.3 稳定的意义4.4 时间复杂度的补充4.5 空间复杂度补充 结语 前言 排序算法是《数据结构与算法》中最基本的算法之一…

QtConcorrent学习、以及与QThread之间的联系

目录 一、QtConcorrent 概述 1、功能 2、特点 3、使用场景 4、QtConcurrent::run 5、应用示例 5、挑战和解决方案 6、QtConcurrent的重要性和价值 二、QFuture 1、主要特点和功能 2、应用示例 三、QtConcorrent与QThread 1、抽象级别和易用性 2. 线程管理和资源利…

C++速通LeetCode简单第6题-环形链表

快慢指针真的很好用&#xff01; /*** Definition for singly-linked list.* struct ListNode {* int val;* ListNode *next;* ListNode(int x) : val(x), next(NULL) {}* };*/ class Solution { public:bool hasCycle(ListNode *head) {//快慢指针ListNode* fast…