仿牛客社区项目4.4——Redis个人用户获得的总赞数(事务、set、string)

在这里插入图片描述
重点:LikeService,Redis编程式事务

1、改key拼接工具类RedisKeyUtil

	private static final String PREFIX_USER_LIKE = "like:user";
    // 某个用户的被点赞总数, value是Object->强转成Integer->intValue()转成int型
    // like:user:userId -> int
    public static String getUserLikeKey(int userId){
        return PREFIX_USER_LIKE + SPLIT + userId;
    }

2、LikeService,编程式事务

保证事务性,一次点赞两处增加,编程式事务。

public void like(int userId, int entityType, int entityId, int entityUserId) {

        // 保证事务性,一次点赞两个增加,编程式事务
        redisTemplate.execute(new SessionCallback() {
            @Override
            public Object execute(RedisOperations operations) throws DataAccessException {
                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);// 点赞
                    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();
}

3、LikeController、discuss-detail.html、discuss.js加参数即可

4、UserController追加个人主页

    // 个人首页
    @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";
    }

5、修改静态页面:profile.html、修改头像动态链接:index.html、discuss-detail

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值