SpringBoot实现物品点赞功能后端代码

SpringBoot实现物品点赞功能
效果:
在这里插入图片描述在这里插入图片描述
在这里插入图片描述在这里插入图片描述
功能:
首先还是一个先发请求返回数据,但是先数据存到了redis中,然后使用springboot定时任务每隔一定时间将数据存到mysql中。这样可以防止redis挂掉之后数据丢失。
数据库设计:
在这里插入图片描述MySQL使用了一张表和另外几张表的一个字段,一张存放点赞信息,就是谁点赞了谁在啥时候。字段存放点赞数量。就是物品信息表。评论表这些。
在这里插入图片描述redis,使用的是hash数据结构,redis_liked存放点赞数据,redis_liked_count存放点赞数量数据。
解释 :
对于 “1::字符串::1 ” 这个是一种存放方式,前面1为objid就是被点赞物品或者评论id,字符串为微信openid每个用户唯一id,后面1为类型区分点赞的是物品还是主评论,子评论。

对于 "“0"” 这个数据则是点赞的状态,1为点赞0为取消点赞对于"1::1"这个前面1是objid就是物品或者子、主评论id,后面则是区别是哪个类型。“0”就是点赞数量。
在这里插入图片描述在这里插入图片描述在这里插入图片描述
在这里插入图片描述后台代码:
前端入口代码:

package com.w.wx.controller;

import com.w.wx.domain.Msg;
import com.w.wx.service.impls.RedisServiceImpl;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;

import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@Slf4j
@RestController
@RequestMapping("/wx/liked")
public class LikedContro {
   

    @Autowired
    private RedisServiceImpl redisService;

    /**
     * 保存点赞数据到redis
     * 点赞数+1
     * 同一个不能点赞两次
     * @param objId
     * @param openid
     * @param type
     * @return
     */
    @RequestMapping("like")
    public Msg saveLikedToRedis(Integer objId,String openid , String type){
   

        redisService.incrementLikedCount(objId, type, openid);

        redisService.saveLikedToRedis(objId,openid,type);

        int oneInfoCount = redisService.getOneInfoCount(objId, type);
        return Msg.success().add("count",oneInfoCount);
    }

    @RequestMapping("unlike")
    public  Msg decrementLikedCount(Integer objId,String openid,String type){
   
        redisService.decrementLikedCount(objId,type,openid);
        redisService.unlikeFromRedis(objId,openid,type);

        int oneInfoCount = redisService.getOneInfoCount(objId, type);
        return Msg.success().add("count",oneInfoCount);
    }
	
	//恢复redis
    @RequestMapping("restore")
    public Msg restoreRedisCountInfo(){
   
        redisService.savaInfoFromDb2Re(0);
        redisService.savaInfoFromDb2Re(1);
        redisService.savaInfoFromDb2Re(2);
        return Msg.success();
    }
}

操作redis代码:

package com.w.wx.service.impls;

import com.w.wx.mapper.LikedMapper;
import com.w.wx.domain.Liked;
import com.w.wx.service.ImagesService;
import com.w.wx.service.RedisService;
import com.w.wx.utils.RedisKeyUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.Cursor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ScanOptions;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.Map;

@Service
@Slf4j
public class RedisServiceImpl implements RedisService {
   

    @Autowired
    private RedisTemplate redisTemplate
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 1
    评论
这里提供一个简单的微信小程序和Spring Boot后端实现、评论和发布的代码示例。 1. 微信小程序代码 在微信小程序中,我们需要实现三个核心功能:点、评论和发布。这里给出一个简单的UI设计和相关的代码实现。 1.1 界面设计 在小程序的界面中,我们需要实现以下几个页面: - 首页:展示所有已发布的文章列表,包括文章标题、作者、发布时间、点数和评论数。 - 文章详情页:展示某一篇文章的详细信息,包括文章标题、作者、发布时间、点数、评论数和文章内容。 - 发布文章页:用户可以在此页面发布自己的文章。 - 评论页:用户可以在此页面查看某一篇文章的所有评论,并可以发表自己的评论。 - 点功能:用户可以在文章详情页中对文章进行点或取消点操作。 - 评论功能:用户可以在文章详情页和评论页中发表评论。 下面是一个简单的UI设计: ![微信小程序界面设计](https://img-blog.csdnimg.cn/20210629131456380.png) 1.2 代码实现 在微信小程序中,我们需要使用`wx.request()`来向后端发送请求。例如,向后端请求所有文章列表: ``` wx.request({ url: 'http://localhost:8080/article/list', success: function (res) { console.log(res.data); // TODO: 处理返回的文章列表数据 } }) ``` 在微信小程序中,我们还需要使用`wx.navigateTo()`和`wx.redirectTo()`等方法来实现页面跳转。例如,跳转到文章详情页: ``` wx.navigateTo({ url: '/pages/article-detail/article-detail?id=' + articleId }) ``` 其他具体实现细节可以参考下面的完整代码。 2. Spring Boot后端代码 在Spring Boot后端中,我们需要实现以下几个核心功能: - 文章列表查询接口:查询所有已发布的文章列表。 - 文章详情查询接口:查询某一篇文章的详细信息。 - 文章发布接口:发布一篇新的文章。 - 评论列表查询接口:查询某一篇文章的所有评论。 - 评论发布接口:发布一条新的评论。 - 点接口:对某一篇文章进行点或取消点操作。 下面给出一个简单的Spring Boot后端实现。 2.1 依赖 在`pom.xml`中添加以下依赖: ``` <dependencies> <dependency> <groupId>org.springframework.boot</groupId> <artifactId>spring-boot-starter-web</artifactId> </dependency> <dependency> <groupId>com.alibaba</groupId> <artifactId>fastjson</artifactId> <version>1.2.62</version> </dependency> </dependencies> ``` 2.2 数据库 这里使用MySQL来存储文章和评论的信息。在MySQL中创建`article`和`comment`表,具体的DDL语句如下: ``` CREATE TABLE `article` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '文章ID', `title` varchar(255) NOT NULL COMMENT '文章标题', `author` varchar(255) NOT NULL COMMENT '文章作者', `content` text NOT NULL COMMENT '文章内容', `create_time` datetime NOT NULL COMMENT '创建时间', `update_time` datetime NOT NULL COMMENT '更新时间', `praise_count` int(11) NOT NULL DEFAULT '0' COMMENT '点数', `comment_count` int(11) NOT NULL DEFAULT '0' COMMENT '评论数', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='文章表'; CREATE TABLE `comment` ( `id` bigint(20) NOT NULL AUTO_INCREMENT COMMENT '评论ID', `article_id` bigint(20) NOT NULL COMMENT '文章ID', `content` text NOT NULL COMMENT '评论内容', `create_time` datetime NOT NULL COMMENT '创建时间', PRIMARY KEY (`id`) ) ENGINE=InnoDB AUTO_INCREMENT=1 DEFAULT CHARSET=utf8mb4 COMMENT='评论表'; ``` 2.3 实体类 在Java中,我们需要定义相应的实体类来映射数据库中的表结构。具体实现如下: 文章实体类`Article.java`: ``` public class Article { private Long id; private String title; private String author; private String content; private Date createTime; private Date updateTime; private Integer praiseCount; private Integer commentCount; // getter 和 setter 方法省略 } ``` 评论实体类`Comment.java`: ``` public class Comment { private Long id; private Long articleId; private String content; private Date createTime; // getter 和 setter 方法省略 } ``` 2.4 DAO层 在DAO层中,我们需要定义相应的接口和实现类来操作数据库。具体实现如下: 文章DAO接口`ArticleDao.java`: ``` public interface ArticleDao { List<Article> list(); Article getById(Long id); int save(Article article); int updatePraiseCount(Long id, Integer delta); int updateCommentCount(Long id, Integer delta); } ``` 文章DAO实现类`ArticleDaoImpl.java`: ``` @Repository public class ArticleDaoImpl implements ArticleDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public List<Article> list() { String sql = "SELECT * FROM article ORDER BY create_time DESC"; return jdbcTemplate.query(sql, new BeanPropertyRowMapper<>(Article.class)); } @Override public Article getById(Long id) { String sql = "SELECT * FROM article WHERE id = ?"; return jdbcTemplate.queryForObject(sql, new Object[]{id}, new BeanPropertyRowMapper<>(Article.class)); } @Override public int save(Article article) { String sql = "INSERT INTO article(title, author, content, create_time, update_time) VALUES(?, ?, ?, ?, ?)"; return jdbcTemplate.update(sql, article.getTitle(), article.getAuthor(), article.getContent(), article.getCreateTime(), article.getUpdateTime()); } @Override public int updatePraiseCount(Long id, Integer delta) { String sql = "UPDATE article SET praise_count = praise_count + ? WHERE id = ?"; return jdbcTemplate.update(sql, delta, id); } @Override public int updateCommentCount(Long id, Integer delta) { String sql = "UPDATE article SET comment_count = comment_count + ? WHERE id = ?"; return jdbcTemplate.update(sql, delta, id); } } ``` 评论DAO接口`CommentDao.java`: ``` public interface CommentDao { List<Comment> listByArticleId(Long articleId); int save(Comment comment); } ``` 评论DAO实现类`CommentDaoImpl.java`: ``` @Repository public class CommentDaoImpl implements CommentDao { @Autowired private JdbcTemplate jdbcTemplate; @Override public List<Comment> listByArticleId(Long articleId) { String sql = "SELECT * FROM comment WHERE article_id = ? ORDER BY create_time ASC"; return jdbcTemplate.query(sql, new Object[]{articleId}, new BeanPropertyRowMapper<>(Comment.class)); } @Override public int save(Comment comment) { String sql = "INSERT INTO comment(article_id, content, create_time) VALUES(?, ?, ?)"; return jdbcTemplate.update(sql, comment.getArticleId(), comment.getContent(), comment.getCreateTime()); } } ``` 2.5 Service层 在Service层中,我们需要定义相应的接口和实现类来处理业务逻辑。具体实现如下: 文章Service接口`ArticleService.java`: ``` public interface ArticleService { List<Article> list(); Article getById(Long id); int save(Article article); int updatePraiseCount(Long id, Boolean add); int updateCommentCount(Long id, Boolean add); } ``` 文章Service实现类`ArticleServiceImpl.java`: ``` @Service public class ArticleServiceImpl implements ArticleService { @Autowired private ArticleDao articleDao; @Override public List<Article> list() { return articleDao.list(); } @Override public Article getById(Long id) { return articleDao.getById(id); } @Override public int save(Article article) { Date now = new Date(); article.setCreateTime(now); article.setUpdateTime(now); return articleDao.save(article); } @Override public int updatePraiseCount(Long id, Boolean add) { Integer delta = add ? 1 : -1; return articleDao.updatePraiseCount(id, delta); } @Override public int updateCommentCount(Long id, Boolean add) { Integer delta = add ? 1 : -1; return articleDao.updateCommentCount(id, delta); } } ``` 评论Service接口`CommentService.java`: ``` public interface CommentService { List<Comment> listByArticleId(Long articleId); int save(Comment comment); } ``` 评论Service实现类`CommentServiceImpl.java`: ``` @Service public class CommentServiceImpl implements CommentService { @Autowired private CommentDao commentDao; @Override public List<Comment> listByArticleId(Long articleId) { return commentDao.listByArticleId(articleId); } @Override public int save(Comment comment) { Date now = new Date(); comment.setCreateTime(now); return commentDao.save(comment); } } ``` 2.6 Controller层 在Controller层中,我们需要定义相应的接口来处理HTTP请求。具体实现如下: 文章Controller类`ArticleController.java`: ``` @RestController @RequestMapping("/article") public class ArticleController { @Autowired private ArticleService articleService; @Autowired private CommentService commentService; @GetMapping("/list") public List<Article> list() { return articleService.list(); } @GetMapping("/detail") public Article detail(Long id) { return articleService.getById(id); } @PostMapping("/publish") public int publish(@RequestBody Article article) { return articleService.save(article); } @PostMapping("/praise") public int praise(Long id, Boolean add) { return articleService.updatePraiseCount(id, add); } @GetMapping("/comment/list") public List<Comment> listComments(Long articleId) { return commentService.listByArticleId(articleId); } @PostMapping("/comment/publish") public int publishComment(@RequestBody Comment comment) { int result = commentService.save(comment); if (result > 0) { articleService.updateCommentCount(comment.getArticleId(), true); } return result; } } ``` 2.7 配置文件 在Spring Boot中,我们需要在`application.properties`或`application.yml`中配置相关参数。例如,配置MySQL连接信息: ``` spring.datasource.url=jdbc:mysql://localhost:3306/test?useSSL=false&serverTimezone=Asia/Shanghai&characterEncoding=utf-8 spring.datasource.username=root spring.datasource.password=123456 spring.datasource.driver-class-name=com.mysql.cj.jdbc.Driver ``` 其他具体实现细节可以参考下面的完整代码。 3. 完整代码 完整的微信小程序和Spring Boot后端代码可以在我的GitHub仓库中查看: - 微信小程序:https://github.com/zhongmingmao/wechat-mini-program-example - Spring Boot后端:https://github.com/zhongmingmao/spring-boot-example

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

weixin_51297617

你的鼓励将是我创作的最大动力

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

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

打赏作者

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

抵扣说明:

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

余额充值