实现功能
重构点赞功能
- 以用户为key,记录点赞数量
- increment(key),decrement(key)
开发个人主页
- 以用户为key,查询点赞数
controller
//查看个人主页:不仅查看自己的主页,还能查看别人的主页
//userId:要查看主页的人的用户id
@RequestMapping(value = "/profile/{userId}",method = RequestMethod.GET)
public String getProfilePage(@PathVariable("userId") int userId,Model model){
User user = userService.findUserById(userId);
if(user==null){
throw new RuntimeException("该用户不存在!");
}
model.addAttribute("user",user);
//用户获赞数量
int likeCount = likeService.findUserLikeCount(userId);
model.addAttribute("likeCount",likeCount);
return "/site/profile";
}
service
//给帖子点赞
public void like(int userId,int entityType,int entityId ,int entityUserId){
//两次操作:一次记录点赞次数,另一次记录该实体获得的点赞数---->redis事务
redisTemplate.execute(new SessionCallback() {
@Override
public Object execute(RedisOperations operations) throws DataAccessException {
//配置点赞key
String entityLikeKey= RedisKeyUtil.getEntityLikeKey(entityType,entityId);
//配置用户获得赞的key
String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId);
Boolean isMember = redisTemplate.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 int findUserLikeCount(int userId){
//配置用户获得赞的key
String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
return count==null?0:count;
}
html
<!-- 个人信息 -->
<div class="media mt-5">
<img th:src="${user.headerUrl}" class="align-self-start mr-4 rounded-circle" alt="用户头像" style="width:50px;">
<div class="media-body">
<h5 class="mt-0 text-warning">
<span th:utext="${user.userName}">nowcoder</span>
<button type="button" class="btn btn-info btn-sm float-right mr-5 follow-btn">关注TA</button>
</h5>
<div class="text-muted mt-3">
<span>注册于 <i class="text-muted" th:text="${#dates.format(user.createTime,'yyyy-MM-dd HH:mm:ss')}">2015-06-12 15:20:12</i></span>
</div>
<div class="text-muted mt-3 mb-5">
<span>关注了 <a class="text-primary" href="followee.html">5</a> 人</span>
<span class="ml-4">关注者 <a class="text-primary" href="follower.html">123</a> 人</span>
<span class="ml-4">获得了 <i class="text-danger" th:text="${likeCount}">87</i> 个赞</span>
</div>
</div>
</div>
js
function like(btn,entityType,entityId,entityUserId){
$.post(
CONTEXT_PATH+"/like",
{"entityType":entityType,"entityId":entityId,"entityUserId":entityUserId},
function(data){
data=$.parseJSON(data);
if(data.code==0){
$(btn).children("i").text(data.likeCount);
$(btn).children("b").text(data.likeStatus==1?'已赞':'赞');
}else{
alert(data.msg);
}
}
);
}