4.4 我收到的赞
程序员文章站
2023-12-25 21:32:39
...
在用户点赞的是时候,增加一个维度。
在RedisKeyUtil中添加
private static final String PREFIX_USER_LIKE = "like:user";
//某个用户的赞
//like:user:userId -> int
public static String getUserLikeKey(int useId){
return PREFIX_USER_LIKE + SPLIT + useId;
}
LikeService
涉及到了多个操作,使用事务,另外,查询要放到事务之外,如果放到事务之内,不会立马就返回查询结果。
//点赞entityUserId:实体作者id
public void like(int userId, int entityType, int entityId, int entityUserId){
redisTemplate.execute(new SessionCallback() {
@Override
public Object execute(RedisOperations operations) throws DataAccessException {
//先拼好两个key
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);
if(operations.opsForValue().get(userLikeKey) == null){
operations.opsForValue().set(userLikeKey, 0);
}
operations.opsForValue().increment(userLikeKey);
}
return operations.exec();//表示的是提交事务
}
});
}
额外添加一个查询某个用户获得的赞的数量的方法
public int findUserLikeCount(int userId){
String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
return count == null ? 0: count.intValue();
}
LikeController
需要额外添加 一个entityUserId参数
@RequestMapping(path="/like",method = RequestMethod.POST)
@ResponseBody
public String like(int entityType, int entityId, int entityUserId){
//当前用户点赞
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);
return CommunityUtil.getJSONString(0,null, map);
}
UserController
显示个人主页时需要把用户收到的赞的总数量放到Model之中去。
@RequestMapping(path="/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";
}