• 4-four: 我收到的赞


    我收到的赞

    重构点赞功能(用上节的功能较为麻烦,需要将用户发布的帖子和评论所获得的赞加起来)

    • 以用户为key,记录点赞数量
    • increment(key), decrement(key)。

    开发个人主页

    • 以用户为key,查询点赞数量

    1.在Redis.Util中增加方法

    // 某个用户的赞
        // like:user:userId -> int
        public static String getUserLikeKey(int userId) {
            return PREFIX_USER_LIKE + SPLIT + userId;
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    2.重构点赞方法: 在LikeService中增加业务,需要保证事务性
    package com.nowcoder.community.service;
    
    import com.nowcoder.community.util.RedisKeyUtil;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.dao.DataAccessException;
    import org.springframework.data.redis.core.RedisOperations;
    import org.springframework.data.redis.core.RedisTemplate;
    import org.springframework.data.redis.core.SessionCallback;
    import org.springframework.stereotype.Service;
    
    @Service
    public class LikeService {
    
        @Autowired
        private RedisTemplate redisTemplate;
    
        // 点赞
        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 long findEntityLikeCount(int entityType, int entityId) {
            String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
            return redisTemplate.opsForSet().size(entityLikeKey);
        }
    
        // 查询某人对某实体的点赞状态
        public int findEntityLikeStatus(int userId, int entityType, int entityId) {
            String entityLikeKey = RedisKeyUtil.getEntityLikeKey(entityType, entityId);
            return redisTemplate.opsForSet().isMember(entityLikeKey, userId) ? 1 : 0;
        }
    
        // 查询某个用户获得的赞
        public int findUserLikeCount(int userId) {
            String userLikeKey = RedisKeyUtil.getUserLikeKey(userId);
            Integer count = (Integer) redisTemplate.opsForValue().get(userLikeKey);
            return count == null ? 0 : count.intValue();
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    4 LikeController.java
    package com.nowcoder.community.controller;
    
    import com.nowcoder.community.entity.User;
    import com.nowcoder.community.service.LikeService;
    import com.nowcoder.community.util.CommunityUtil;
    import com.nowcoder.community.util.HostHolder;
    import org.springframework.beans.factory.annotation.Autowired;
    import org.springframework.stereotype.Controller;
    import org.springframework.web.bind.annotation.RequestMapping;
    import org.springframework.web.bind.annotation.RequestMethod;
    import org.springframework.web.bind.annotation.ResponseBody;
    
    import java.util.HashMap;
    import java.util.Map;
    
    @Controller
    public class LikeController {
    
        @Autowired
        private LikeService likeService;
    
        @Autowired
        private HostHolder hostHolder;
    
        @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);
        }
    
    }
    
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    5. 对页面做处理

    在帖子详情页面,新添加传入相应的参数,
    在这里插入图片描述
    在处理的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);
                }
            }
        );
    }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15

    对实体的作者新添加了一个KEY,这个KEY会随着点赞次数的增加而自增,相应的随着取消点赞而自减,然后,可以查看最后这个KEY的数量,从而判断用户收到了多少的赞。

    个人主页的编码

    1. 在UserController.java中增加代码

    (注意,可以查看自己的主页,也可以查看他人的主页)

        // 个人主页
        @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);//注意要将service对象注入
            model.addAttribute("likeCount", likeCount);//将数量发送给页面
            return "/site/profile";//返回指定模板
        }
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    2. 在Index.html中增加代码

    在这里插入图片描述
    在这里插入图片描述
    profile.html

    doctype html>
    <html lang="en" xmlns:th="http://www.thymeleaf.org">
    <head>
    	<meta charset="utf-8">
    	<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
    	<link rel="icon" href="https://static.nowcoder.com/images/logo_87_87.png"/>
    	<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" crossorigin="anonymous">
    	<link rel="stylesheet" th:href="@{/css/global.css}" />
    	<title>牛客网-个人主页title>
    head>
    <body>
    	<div class="nk-container">
    		
    		<header class="bg-dark sticky-top" th:replace="index::header">
    			<div class="container">
    				
    				<nav class="navbar navbar-expand-lg navbar-dark">
    					
    					<a class="navbar-brand" href="#">a>
    					<button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    						<span class="navbar-toggler-icon">span>
    					button>
    					
    					<div class="collapse navbar-collapse" id="navbarSupportedContent">
    						<ul class="navbar-nav mr-auto">
    							<li class="nav-item ml-3 btn-group-vertical">
    								<a class="nav-link" href="../index.html">首页a>
    							li>
    							<li class="nav-item ml-3 btn-group-vertical">
    								<a class="nav-link position-relative" href="letter.html">消息<span class="badge badge-danger">12span>a>
    							li>
    							<li class="nav-item ml-3 btn-group-vertical">
    								<a class="nav-link" href="register.html">注册a>
    							li>
    							<li class="nav-item ml-3 btn-group-vertical">
    								<a class="nav-link" href="login.html">登录a>
    							li>
    							<li class="nav-item ml-3 btn-group-vertical dropdown">
    								<a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
    									<img src="http://images.nowcoder.com/head/1t.png" class="rounded-circle" style="width:30px;"/>
    								a>
    								<div class="dropdown-menu" aria-labelledby="navbarDropdown">
    									<a class="dropdown-item text-center" href="profile.html">个人主页a>
    									<a class="dropdown-item text-center" href="setting.html">账号设置a>
    									<a class="dropdown-item text-center" href="login.html">退出登录a>
    									<div class="dropdown-divider">div>
    									<span class="dropdown-item text-center text-secondary">nowcoderspan>
    								div>
    							li>
    						ul>
    						
    						<form class="form-inline my-2 my-lg-0" action="search.html">
    							<input class="form-control mr-sm-2" type="search" aria-label="Search" />
    							<button class="btn btn-outline-light my-2 my-sm-0" type="submit">搜索button>
    						form>
    					div>
    				nav>
    			div>
    		header>
    
    		
    		<div class="main">
    			<div class="container">
    				
    				<div class="position-relative">
    					<ul class="nav nav-tabs">
    						<li class="nav-item">
    							<a class="nav-link active" href="profile.html">个人信息a>
    						li>
    						<li class="nav-item">
    							<a class="nav-link" href="my-post.html">我的帖子a>
    						li>
    						<li class="nav-item">
    							<a class="nav-link" href="my-reply.html">我的回复a>
    						li>
    					ul>
    				div>
    				
    				<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}">nowcoderspan>
    							<button type="button" class="btn btn-info btn-sm float-right mr-5 follow-btn">关注TAbutton>
    						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:12i>span>
    						div>
    						<div class="text-muted mt-3 mb-5">
    							<span>关注了 <a class="text-primary" href="followee.html">5a>span>
    							<span class="ml-4">关注者 <a class="text-primary" href="follower.html">123a>span>
    							<span class="ml-4">获得了 <i class="text-danger" th:text="${likeCount}">87i> 个赞span>
    						div>
    					div>
    				div>
    			div>
    		div>
    
    		
    		<footer class="bg-dark">
    			<div class="container">
    				<div class="row">
    					
    					<div class="col-4 qrcode">
    						<img src="https://uploadfiles.nowcoder.com/app/app_download.png" class="img-thumbnail" style="width:136px;" />
    					div>
    					
    					<div class="col-8 detail-info">
    						<div class="row">
    							<div class="col">
    								<ul class="nav">
    									<li class="nav-item">
    										<a class="nav-link text-light" href="#">关于我们a>
    									li>
    									<li class="nav-item">
    										<a class="nav-link text-light" href="#">加入我们a>
    									li>
    									<li class="nav-item">
    										<a class="nav-link text-light" href="#">意见反馈a>
    									li>
    									<li class="nav-item">
    										<a class="nav-link text-light" href="#">企业服务a>
    									li>
    									<li class="nav-item">
    										<a class="nav-link text-light" href="#">联系我们a>
    									li>
    									<li class="nav-item">
    										<a class="nav-link text-light" href="#">免责声明a>
    									li>
    									<li class="nav-item">
    										<a class="nav-link text-light" href="#">友情链接a>
    									li>
    								ul>
    							div>
    						div>
    						<div class="row">
    							<div class="col">
    								<ul class="nav btn-group-vertical company-info">
    									<li class="nav-item text-white-50">
    										公司地址:北京市朝阳区大屯路东金泉时代3-2708北京牛客科技有限公司
    									li>
    									<li class="nav-item text-white-50">
    										联系方式:010-60728802(电话)    admin@nowcoder.com
    									li>
    									<li class="nav-item text-white-50">
    										牛客科技©2018 All rights reserved
    									li>
    									<li class="nav-item text-white-50">
    										京ICP备14055008号-4     
    										<img src="http://static.nowcoder.com/company/images/res/ghs.png" style="width:18px;" />
    										京公网安备 11010502036488号
    									li>
    								ul>
    							div>
    						div>
    					div>
    				div>
    			div>
    		footer>
    	div>
    
    	<script src="https://code.jquery.com/jquery-3.3.1.min.js" crossorigin="anonymous">script>
    	<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js" crossorigin="anonymous">script>
    	<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js" crossorigin="anonymous">script>
    	<script th:src="@{/js/global.js}">script>
    	<script th:src="@{/js/profile.js}">script>
    body>
    html>
    
    • 1
    • 2
    • 3
    • 4
    • 5
    • 6
    • 7
    • 8
    • 9
    • 10
    • 11
    • 12
    • 13
    • 14
    • 15
    • 16
    • 17
    • 18
    • 19
    • 20
    • 21
    • 22
    • 23
    • 24
    • 25
    • 26
    • 27
    • 28
    • 29
    • 30
    • 31
    • 32
    • 33
    • 34
    • 35
    • 36
    • 37
    • 38
    • 39
    • 40
    • 41
    • 42
    • 43
    • 44
    • 45
    • 46
    • 47
    • 48
    • 49
    • 50
    • 51
    • 52
    • 53
    • 54
    • 55
    • 56
    • 57
    • 58
    • 59
    • 60
    • 61
    • 62
    • 63
    • 64
    • 65
    • 66
    • 67
    • 68
    • 69
    • 70
    • 71
    • 72
    • 73
    • 74
    • 75
    • 76
    • 77
    • 78
    • 79
    • 80
    • 81
    • 82
    • 83
    • 84
    • 85
    • 86
    • 87
    • 88
    • 89
    • 90
    • 91
    • 92
    • 93
    • 94
    • 95
    • 96
    • 97
    • 98
    • 99
    • 100
    • 101
    • 102
    • 103
    • 104
    • 105
    • 106
    • 107
    • 108
    • 109
    • 110
    • 111
    • 112
    • 113
    • 114
    • 115
    • 116
    • 117
    • 118
    • 119
    • 120
    • 121
    • 122
    • 123
    • 124
    • 125
    • 126
    • 127
    • 128
    • 129
    • 130
    • 131
    • 132
    • 133
    • 134
    • 135
    • 136
    • 137
    • 138
    • 139
    • 140
    • 141
    • 142
    • 143
    • 144
    • 145
    • 146
    • 147
    • 148
    • 149
    • 150
    • 151
    • 152
    • 153
    • 154
    • 155
    • 156
    • 157
    • 158
    • 159
    • 160
    • 161
    • 162
    • 163
    • 164
    • 165
    • 166
    • 167
    • 168

    在这里插入图片描述

    将之前的测试数据删除,重新构造点赞数据测试即可
    在这里插入图片描述


    注意:Redis存的是Key Value的键值对,对其用户key,设置一个value,可以存储该用户被点赞的数据量。

  • 相关阅读:
    图片如何转PDF格式?这里有你想知道的方法
    探秘TikTok社群:短视频中的共同体验
    K8S部署Java项目 pod报错 logs日志内容:no main manifest attribute, in app.jar
    EasyOCR 识别模型训练
    c++设计模式之观察者模式(消息订阅模式)
    复盘在项目管理中的应用
    图片压缩软件大全-免费图片压缩软件排名
    Qt学习笔记NO2. QCustomPlot 学习使用笔记
    在Microsoft Exchange Server 2007中安装SSL证书的教程
    大健康行业千城万企信用建设工作启动大会在京召开
  • 原文地址:https://blog.csdn.net/qq_41026725/article/details/128134281