也是将数据存储到redis中,实现统计
package com.nowcoder.community.util;public class RedisKeyUtil {private static final String SPLIT = ":";private static final String PREFIX_ENTITY_LIKE = "like:entity";private static final String PREFIX_USER_LIKE = "like:user";private static final String PREFIX_FOLLOWEE = "followee";//声明两个前缀private static final String PREFIX_FOLLOWER = "follower";//关注了某人,将目标存在下,private static final String PREFIX_KAPTCHA = "kaptcha";private static final String PREFIX_TICKET = "ticket";private static final String PREFIX_USER = "user";// 某个实体的赞// like:entity:entityType:entityId -> set(userId)public static String getEntityLikeKey(int entityType, int entityId) {return PREFIX_ENTITY_LIKE + SPLIT + entityType + SPLIT + entityId;}// 某个用户的赞// like:user:userId -> intpublic static String getUserLikeKey(int userId) {return PREFIX_USER_LIKE + SPLIT + userId;}// 某个用户关注的实体,拼key的方法,存的时候,存有序集合,zset可以排序// followee:userId:entityType -> zset(entityId,now);//某个用户关注某个实体,以当前时间排序,能应付更好的需求变化public static String getFolloweeKey(int userId, int entityType) {return PREFIX_FOLLOWEE + SPLIT + userId + SPLIT + entityType;}// 某个实体拥有的粉丝// follower:entityType:entityId -> zset(userId,now)public static String getFollowerKey(int entityType, int entityId) {return PREFIX_FOLLOWER + SPLIT + entityType + SPLIT + entityId;}// 用户public static String getUserKey(int userId) {return PREFIX_USER + SPLIT + userId;}}
package com.nowcoder.community.service;import com.nowcoder.community.entity.User;
import com.nowcoder.community.util.CommunityConstant;
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;import java.util.*;@Service
public class FollowService implements CommunityConstant {@Autowiredprivate RedisTemplate redisTemplate;//注入Redis相应的组件@Autowiredprivate UserService userService;//将用户组件注入public void follow(int userId, int entityType, int entityId) {redisTemplate.execute(new SessionCallback() {//一项业务有两项存储,要保证其事务性@Overridepublic Object execute(RedisOperations operations) throws DataAccessException {String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);//关注是用户关注String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);operations.multi();//启用事务,在中间做两次存储的操作operations.opsForZSet().add(followeeKey, entityId, System.currentTimeMillis());//分数是当前时间,转成毫秒时间operations.opsForZSet().add(followerKey, userId, System.currentTimeMillis());return operations.exec();//执行事务}});}//取消关注的代码逻辑public void unfollow(int userId, int entityType, int entityId) {redisTemplate.execute(new SessionCallback() {@Overridepublic Object execute(RedisOperations operations) throws DataAccessException {String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);operations.multi();operations.opsForZSet().remove(followeeKey, entityId);//与上一方法的区别只是将数据移除operations.opsForZSet().remove(followerKey, userId);return operations.exec();}});}// 查询关注的实体的数量public long findFolloweeCount(int userId, int entityType) {String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);return redisTemplate.opsForZSet().zCard(followeeKey);}// 查询实体的粉丝的数量public long findFollowerCount(int entityType, int entityId) {String followerKey = RedisKeyUtil.getFollowerKey(entityType, entityId);return redisTemplate.opsForZSet().zCard(followerKey);}// 查询当前用户是否已关注该实体public boolean hasFollowed(int userId, int entityType, int entityId) {String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);return redisTemplate.opsForZSet().score(followeeKey, entityId) != null;}// 查询某用户关注的人public List
package com.nowcoder.community.controller;import com.nowcoder.community.entity.Page;
import com.nowcoder.community.entity.User;
import com.nowcoder.community.service.FollowService;
import com.nowcoder.community.service.UserService;
import com.nowcoder.community.util.CommunityConstant;
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.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;import java.util.List;
import java.util.Map;@Controller
public class FollowController implements CommunityConstant {@Autowiredprivate FollowService followService;//注入service@Autowiredprivate HostHolder hostHolder;@Autowiredprivate UserService userService;@RequestMapping(path = "/follow", method = RequestMethod.POST)//关注是一个异步请求@ResponseBodypublic String follow(int entityType, int entityId) {User user = hostHolder.getUser();//获取当前登陆用户;followService.follow(user.getId(), entityType, entityId);return CommunityUtil.getJSONString(0, "已关注!");//异步请求,返回JSON}@RequestMapping(path = "/unfollow", method = RequestMethod.POST)//取消关注的逻辑类似@ResponseBodypublic String unfollow(int entityType, int entityId) {User user = hostHolder.getUser();followService.unfollow(user.getId(), entityType, entityId);return CommunityUtil.getJSONString(0, "已取消关注!");}@RequestMapping(path = "/followees/{userId}", method = RequestMethod.GET)public String getFollowees(@PathVariable("userId") int userId, Page page, Model model) {User user = userService.findUserById(userId);if (user == null) {throw new RuntimeException("该用户不存在!");}model.addAttribute("user", user);page.setLimit(5);page.setPath("/followees/" + userId);page.setRows((int) followService.findFolloweeCount(userId, ENTITY_TYPE_USER));List> userList = followService.findFollowees(userId, page.getOffset(), page.getLimit());if (userList != null) {for (Map map : userList) {User u = (User) map.get("user");map.put("hasFollowed", hasFollowed(u.getId()));}}model.addAttribute("users", userList);return "/site/followee";}@RequestMapping(path = "/followers/{userId}", method = RequestMethod.GET)public String getFollowers(@PathVariable("userId") int userId, Page page, Model model) {User user = userService.findUserById(userId);if (user == null) {throw new RuntimeException("该用户不存在!");}model.addAttribute("user", user);page.setLimit(5);page.setPath("/followers/" + userId);page.setRows((int) followService.findFollowerCount(ENTITY_TYPE_USER, userId));List> userList = followService.findFollowers(userId, page.getOffset(), page.getLimit());if (userList != null) {for (Map map : userList) {User u = (User) map.get("user");map.put("hasFollowed", hasFollowed(u.getId()));}}model.addAttribute("users", userList);return "/site/follower";}private boolean hasFollowed(int userId) {if (hostHolder.getUser() == null) {return false;}return followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);}}
这里演示关注某个用户
在CommunityConstant.java接口中添加“人”所代表的实体类型。
/*** 实体类型: 用户*/int ENTITY_TYPE_USER = 3;

$(function(){$(".follow-btn").click(follow);
});function follow() {var btn = this;if($(btn).hasClass("btn-info")) {// 关注TA$.post(CONTEXT_PATH + "/follow",{"entityType":3,"entityId":$(btn).prev().val()},//ID值从页面中显示function(data) {data = $.parseJSON(data);//处理从服务器返回的结果,先转成JSON对象if(data.code == 0) {//若服务器返回的结果是0 ,关注成功,否则不成功window.location.reload();//刷新页面,不更改样式} else {alert(data.msg);//返回提示信息}});// $(btn).text("已关注").removeClass("btn-info").addClass("btn-secondary");} else {// 取消关注$.post(CONTEXT_PATH + "/unfollow",{"entityType":3,"entityId":$(btn).prev().val()},function(data) {data = $.parseJSON(data);if(data.code == 0) {window.location.reload();} else {alert(data.msg);}});//$(btn).text("关注TA").removeClass("btn-secondary").addClass("btn-info");}
}
注意,关注数量和关注状态此时还没有改变;检验时只能从Redis中查询结果
在服务层FollowService.java添加方法
public boolean hasFollowed(int userId, int entityType, int entityId) {String followeeKey = RedisKeyUtil.getFolloweeKey(userId, entityType);return redisTemplate.opsForZSet().score(followeeKey, entityId) != null;//查询用户对于该实体的分数,如果有分数,则就是关注了}
// 个人主页@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);// 关注数量long followeeCount = followService.findFolloweeCount(userId, ENTITY_TYPE_USER);model.addAttribute("followeeCount", followeeCount);//得到当前用户的关注数量并传递给模板// 粉丝数量long followerCount = followService.findFollowerCount(ENTITY_TYPE_USER, userId);model.addAttribute("followerCount", followerCount);//粉丝的数量传递给模板// 是否已关注boolean hasFollowed = false;//当前的登陆用户是否对某用户已经关注if (hostHolder.getUser() != null) {//当前用户不是空时才有可能关注,所以要做判断hasFollowed = followService.hasFollowed(hostHolder.getUser().getId(), ENTITY_TYPE_USER, userId);}model.addAttribute("hasFollowed", hasFollowed);return "/site/profile";}
注意判断用户不关注自己,点击某人的详细信息页面时,不显示自己关注自己的情况
