BBS论坛项目相关-10:Redis关注模块和优化登陆模块
需求
关注,取消关注功能
统计用户粉丝数,关注数
A关注了B,则A是B的follower,B是A的Followee(目标)
关注的目标可以是用户,帖子,题目等,在实现时将这些目标抽象为实体
关注
为了便于统计,将关注人和被关注对象都设置一个key键值,这样用户关注时,用户自己的关注列表会进行统计,被关注的对象的粉丝列表也会进行统计
实体类型:帖子:1,评论:2,用户:3
用户的关注列表:
Followee关注目标的key:用户可能关注的是一个用户对象,也可能是一个帖子。
followee:userId:entityType -> zset(entityId,now)
add(K key, V value, double score)
用zset进行存储,可以进行排序,value中存储entityId,即关注的那个对象id,分数为当前时间
// followee:userId:entityType -> zset(entityId,now)
public static String getFolloweeKey(int userId, int entityType) {
return PREFIX_FOLLOWEE + SPLIT + userId + SPLIT + entityType;
}
某个实体或某个用户的粉丝列表:Follower某个实体拥有的粉丝
follower:entityType:entityId -> zset(userId,now)
用zset进行存储,可以进行排序,value中存储userid,即粉丝对象id,分数为当前时间
// follower:entityType:entityId -> zset(userId,now)
public static String getFollowerKey(int entityType, int entityId) {
return PREFIX_FOLLOWER + SPLIT + entityType + SPLIT + entityId;
}
关注
用户关注实体,实体粉丝增加,这两个事件是同时发生的,需要当做事务处理
public void follow(int userId, int entityType, int entityId) {
redisTemplate.execute(new SessionCallback() {
@Override
public 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() {
@Override
public 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();
}
});
}
controller层
public String follow(int entityType, int entityId) {
User user = hostHolder.getUser();
followService.follow(user.getId(), entityType, entityId);
return CommunityUtil.getJSONString(0, "已关注!");
}
@RequestMapping(path = "/unfollow", method = RequestMethod.POST)
@ResponseBody
public String unfollow(int entityType, int entityId) {
User user = hostHolder.getUser();
followService.unfollow(user.getId(), entityType, entityId);
return CommunityUtil.getJSONString(0, "已取消关注!");
}
通过js样式进行处理关注事件和取消关注事件
function follow() {
var btn = this;
if($(btn).hasClass("btn-info")) {
// 关注TA
$.post(
CONTEXT_PATH + "/follow",
{
"entityType":3,"entityId":$(btn).prev().val()},
function(data) {
data = $.parseJSON(data);
if(data.code == 0) {
window.location.reload();//成功关注,则刷新页面
} else {
alert(data.msg);
}
}
);
// $(btn).text("已关注").removeClass("btn-info").addClass("btn-secondary");
} else {
// 取消关注
$.post(
CONTEXT_PATH + "/unfollow",