问答社区-我收到的赞
需求:
1、重构点赞功能
- 以用户为key,记录点赞数量
- increment,decrement
2、开发个人主页
- 以用户为key,查询点赞数量
步骤:
1、增加新的rediskey
/** * 某个用户的收到的赞 * 格式:like:user:userID */ public static String getUserLikeKey(int userId) { return PREFIX_USER_LIKE + SPLIT + userId; }
2、likeService中新增方法,查询某个用户获得赞的数量,并且重构点赞方法,增加事务管理
//查询某个用户获得赞的数量 public int findUserLikeCount(int userId){ String userLikeKey = RedisKeyUtil.getUserLikeKey(userId); Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey); return count == null ? 0 : count.intValue(); } //点赞 public void like(int userId, int entityType, int entityId, int entityUserId) { redisTemplate.execute(new SessionCallback() { @Nullable @Override public Object execute(RedisOperations redisOperations) throws DataAccessException { String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId); String userLikeKey = RedisKeyUtil.getUserLikeKey(entityUserId); Boolean isMember = redisOperations.opsForSet().isMember(entityLikeKey, userId); redisOperations.multi(); if(isMember){ redisOperations.opsForSet().remove(entityLikeKey,userId); redisOperations.opsForValue().decrement(userLikeKey); }else { redisOperations.opsForSet().add(entityLikeKey,userId); redisOperations.opsForValue().increment(userLikeKey); } return redisOperations.exec(); } }); }