课程说明
- 圈子实现点赞、喜欢功能
- 圈子实现评论
- 圈子实现评论的点赞
- 小视频功能介绍
- FastDFS入门学习
- 实现发布小视频功能
- 实现查询小视频列表功能
1、圈子点赞实现分析
在圈子功能中,对于圈子的点赞、喜欢、评论等均可理解为用户对动态的评论(Comment),在quanzi_comment表中使用commentType进行区分。
在具体的实现中,需要将点赞数、某用户是否点赞等数据保存到Reds中,以减轻MongoDB的压力。
具体存储结构如下:
说明:在Redis的存储结构中,采用的是Hash存储,这样的好处就在于一条动态的点赞、喜欢等数据都会集中的存储到一起,从而减少了Redis中数据条数。
2、点赞
2.1、定义枚举
为了规范使用CommentType,所以将其定义为枚举类型。
package com.tanhua.dubbo.server.enums;
/**
* 评论类型:1-点赞,2-评论,3-喜欢
*/
public enum CommentType {
LIKE(1), COMMENT(2), LOVE(3);
int type;
CommentType(int type) {
this.type = type;
}
public int getType() {
return type;
}
}
2.2、dubbo服务
2.2.1、定义接口
package com.tanhua.dubbo.server.api;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.PageInfo;
public interface QuanZiApi {
//........此处忽略其他代码..........
/**
* 根据id查询动态
*
* @param id 动态id
* @return
*/
Publish queryPublishById(String id);
/**
* 点赞
*
* @param userId
* @param publishId
* @return
*/
Boolean likeComment(Long userId, String publishId);
/**
* 取消点赞
*
* @param userId
* @param publishId
* @return
*/
Boolean disLikeComment(Long userId, String publishId);
/**
* 查询点赞数
*
* @param publishId
* @return
*/
Long queryLikeCount(String publishId);
/**
* 查询用户是否点赞该动态
*
* @param userId
* @param publishId
* @return
*/
Boolean queryUserIsLike(Long userId, String publishId);
}
2.2.2、编写实现
package com.tanhua.dubbo.server.api;
@Service(version = "1.0.0")
@Slf4j
public class QuanZiApiImpl implements QuanZiApi {
//评论数据存储在Redis中key的前缀
private static final String COMMENT_REDIS_KEY_PREFIX = "QUANZI_COMMENT_";
//用户是否点赞的前缀
private static final String COMMENT_USER_LIEK_REDIS_KEY_PREFIX = "USER_LIKE_";
//用户是否喜欢的前缀
private static final String COMMENT_USER_LOVE_REDIS_KEY_PREFIX = "USER_LOVE_";
@Autowired
private MongoTemplate mongoTemplate;
@Autowired
private RedisTemplate<String, String> redisTemplate;
//........此处忽略其他代码..........
@Override
public Publish queryPublishById(String id) {
return this.mongoTemplate.findById(new ObjectId(id), Publish.class);
}
@Override
public Boolean likeComment(Long userId, String publishId) {
//判断该用户是否已经点赞,如果已经点赞就直接返回
if (this.queryUserIsLike(userId, publishId)) {
return false;
}
//保存Comment数据
Boolean result = this.saveComment(userId, publishId, CommentType.LIKE, null);
if (!result) {
return false;
}
//修改redis中的点赞数以及是否点赞
//修改点赞数
String redisKey = this.getCommentRedisKeyPrefix(publishId);
String hashKey = CommentType.LIKE.toString();
this.redisTemplate.opsForHash().increment(redisKey, hashKey, 1);
//用户是否点赞
String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");
return true;
}
private String getCommentRedisKeyPrefix(String publishId) {
return COMMENT_REDIS_KEY_PREFIX + publishId;
}
private String getCommentUserLikeRedisKeyPrefix(Long userId) {
return COMMENT_USER_LIKE_REDIS_KEY_PREFIX + userId;
}
@Override
public Boolean disLikeComment(Long userId, String publishId) {
//判断用户是否已经点赞,如果没有点赞就返回
if (!this.queryUserIsLike(userId, publishId)) {
return false;
}
//删除评论数据
Boolean result = this.removeComment(userId, publishId, CommentType.LIKE);
if (!result) {
return false;
}
//修改Redis中的数据
//修改点赞数
String redisKey = this.getCommentRedisKeyPrefix(publishId);
String hashKey = CommentType.LIKE.toString();
this.redisTemplate.opsForHash().increment(redisKey, hashKey, -1);
//用户是否点赞
String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
this.redisTemplate.opsForHash().delete(redisKey, userHashKey);
return true;
}
@Override
public Long queryLikeCount(String publishId) {
//从Redis中命中查询,如果命中直接返回即可
String redisKey = this.getCommentRedisKeyPrefix(publishId);
String hashKey = CommentType.LIKE.toString();
Object data = this.redisTemplate.opsForHash().get(redisKey, hashKey);
if (ObjectUtil.isNotEmpty(data)) {
return Convert.toLong(data);
}
//查询Mongodb
Long count = this.queryCommentCount(publishId, CommentType.LIKE);
//写入Redis中
this.redisTemplate.opsForHash().put(redisKey, hashKey, String.valueOf(count));
return count;
}
@Override
public Boolean queryUserIsLike(Long userId, String publishId) {
//从redis中查询数据
String redisKey = this.getCommentRedisKeyPrefix(publishId);
String userHashKey = this.getCommentUserLikeRedisKeyPrefix(userId);
Object data = this.redisTemplate.opsForHash().get(redisKey, userHashKey);
if (ObjectUtil.isNotEmpty(data)) {
return StrUtil.equals(Convert.toStr(data), "1");
}
//查询Mongodb,确定是否已经点赞
Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
.and("userId").is(userId)
.and("commentType").is(CommentType.LIKE)
);
long count = this.mongoTemplate.count(query, Comment.class);
if(count == 0){
return false;
}
//写入到redis中
this.redisTemplate.opsForHash().put(redisKey, userHashKey, "1");
return true;
}
/**
* 保存Comment
*
* @return
*/
private Boolean saveComment(Long userId, String publishId,
CommentType commentType, String content) {
try {
Comment comment = new Comment();
comment.setId(ObjectId.get());
comment.setUserId(userId);
comment.setPublishId(new ObjectId(publishId));
// 评论类型
comment.setCommentType(commentType.getType());
// 内容
comment.setContent(content);
comment.setCreated(System.currentTimeMillis());
Publish publish = this.queryPublishById(publishId);
//TODO 其他评论对象,暂不处理
comment.setPublishUserId(publish.getUserId());
this.mongoTemplate.save(comment);
return true;
} catch (Exception e) {
log.error("保存Comment出错~ userId = " + userId + ", publishId = " + publishId + ", commentType = " + commentType, e);
}
return false;
}
/**
* 删除评论数据
*
* @param userId
* @param publishId
* @param commentType
* @return
*/
private Boolean removeComment(Long userId, String publishId, CommentType commentType) {
Query query = Query.query(Criteria.where("userId").is(userId)
.and("publishId").is(new ObjectId(publishId))
.and("commentType").is(commentType.getType())
);
return this.mongoTemplate.remove(query, Comment.class).getDeletedCount() > 0;
}
/**
* 查询数量
*
* @param publishId
* @param commentType
* @return
*/
private Long queryCommentCount(String publishId, CommentType commentType) {
Query query = Query.query(Criteria.where("publishId").is(new ObjectId(publishId))
.and("commentType").is(commentType.getType())
);
return this.mongoTemplate.count(query, Comment.class);
}
}
2.2.3、编写测试用例
package com.tanhua.dubbo.server.api;
import com.tanhua.dubbo.server.pojo.Publish;
import com.tanhua.dubbo.server.vo.PageInfo;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.test.context.SpringBootTest;
import org.springframework.test.context.junit4.SpringRunner;
@RunWith(SpringRunner.class)
@SpringBootTest
public class TestQuanZiApi {
@Autowired
private QuanZiApi quanZiApi;
//........此处忽略其他代码..........
@Test
public void testLike(){
Long userId = 1L;
String publishId = "5fae53947e52992e78a3afb1";
Boolean data = this.quanZiApi.queryUserIsLike(userId, publishId);
System.out.println(data);
System.out.println(this.quanZiApi.likeComment(userId, publishId));
System.out.println(this.quanZiApi.queryLikeCount(publishId));
System.out.println(this.quanZiApi.disLikeComment(userId, publishId));
System.out.println(this.quanZiApi.queryLikeCount(publishId));
}
}
2.3、APP接口服务
点赞接口地址:https://mock-java.itheima.net/project/35/interface/api/707
从接口文档来看,点赞完成后需要返回点赞数。
2.3.1、编写接口服务
//com.tanhua.server.controller.QuanZiController
/**
* 点赞
*
* @param publishId
* @return
*/
@GetMapping("/{id}/like")
public ResponseEntity<Long> likeComment(@PathVariable("id") String publishId) {
try {
Long likeCount = this.quanZiService.likeComment(publishId);
if (likeCount != null) {
return ResponseEntity.ok(likeCount);
}
} catch (Exception e) {
e.printStackTrace();
}
return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR)