4.5 关注、取消关注

121 阅读1分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第23天,点击查看活动详情

4.5 关注、取消关注

image-20220722073112210

关注、取消关注

RedisKeyUtil 里增加两个方法去生成key

因为关注、取关比较高频,所以我们存到key里,所以我们在 RedisKeyUtil 里增加两个方法去生成key

private static final String PREFIX_FOLLOWEE = "followee";
private static final String PREFIX_FOLLOWER = "follower";
    // 某个用户关注的实体
    // followee:userId:entityType -> zset(entityId,now)    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;
    }

image-20220722094852771

业务层(Service)

FollowService处理关注、取消关注业务:

@Service
public class FollowService {

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private UserService userService;

    // 关注
    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();
            }
        });
    }
}

image-20220722095248414

在常量接口CommunityConstant中定义一个常量表示实体类型是User

image-20220722095403999

表现层(Controller和themeleaf模板)

image-20220722095600523

然后是处理展示个人主页profile.html的模板

image-20220722095844724

然后是处理上面关注按钮的profile.js

image-20220722100114337

在用户主页显示该用户关注数、粉丝数

在主页显示正确的状态和数量,主页是通过UserController访问的

image-20220722101644819

image-20220722101747941

展示个人主页的模板profile.html:

image-20220722102036863