app好友接口设计方案

来源:互联网 发布:青岛淘宝美工速成班 编辑:程序博客网 时间:2024/05/29 13:08

有关社交类的app,一般都会涉及到好友部分,今天我们就来谈一谈好友接口的设计方法。

首先,这个接口包含三个方法,添加好友,删除好友,获得好友列表。

第一步 设计pojo表

 /**     *     */    private String id;    /**     * 用户id     */    private String userId;    /**     * 朋友ID     */    private String friendId;    /**     * 创建时间     */    private Date createTime;    /**     *保留字段     */    private Integer state;  

这些字段基本上就够用了,名字随便起,最后一个位保留字段,用于必要时的标记字段,数据库的设计原则易多不易少。

然后我这里把数据库设计好后,用mybatis的插件逆向生成对应的mapper,mapper.xml,vo,dao等等一些自己定义的所需要的文件。

第二步,书写业务层代码。

你需要四个方法,添加好友,删除好友,获得好友列表,判断两个人是否为好友关系。

这里值的注意的一点是,在添加删除好友的时候(userId1,userId2)和(userId2,userId1)是一组数据,不要重复添加和删除。可以做一个限制,就是始终让userId2>userId1。

添加好友:

 public void addUserFriend(String fromId, String toId) {        if(getFriendRelation(fromId,toId)){            throw new BusinessException(ErrorCode.FRIEND_ALREADY_EXIST);        }        /**         *         * 设计规则:         *         * <UserID 1, UserID 2> 和 <UserID 2, UserID 1> 是一样的记录,不要重复添加         * 为了快速判断两个人是不是好友,可以在程序层插入数据前加一个限制 UserID1 < UserID2         * 快速得到一个人的好友列表,查询时用 UNION ALL,不是 UNION         * 如果为了再高效,加入缓存层(如Redis)         */        UserFriend userFriend;        if (Objects.equals(fromId, toId)) {            return;        } else if (Integer.parseInt(fromId) < Integer.parseInt(toId)) {            userFriend = new UserFriend(fromId, toId);        } else {            userFriend = new UserFriend(toId, fromId);        }        // 创建UUID        userFriend.setId(userFriend.getUUID());        userFriend.setState(1);        userFriendDAO.add(userFriend);    }

判断是否为好友关系:

/**     * 判断是否有好友关系     * true:是好友     * @param fromId     * @param toId     * @return     */    public boolean getFriendRelation(String fromId, String toId){        UserFriendModel userFriend;        if (Integer.parseInt(fromId) < Integer.parseInt(toId)) {            userFriend = new UserFriendModel(fromId, toId);        } else {            userFriend = new UserFriendModel(toId, fromId);        }        // 判断是否有好友关系        return !ObjectUtils.isNullCollection(userFriendDAO.queryByList(userFriend));    }

其它的删除和获取列表,可以参考着写。还有最后一个要注意的地方就是对应的mapper.xml里面的查询方法。

<!-- 这里用union all 的原因是因为效率问题,而且设计规则上是userId比FriendId小,所以不需要用union去重-->    <select id="queryUserFriend" resultMap="BaseResultMap"            parameterType="java.lang.String">        select        <include refid="baseColumnList"/>        from user_friend u1 where u1.user_id = #{userId}        union all        select        <include refid="baseColumnList"/>        from user_friend u2 where u2.friend_id = #{userId}    </select>

这样以来基本上就没有什么问题了。对了,还有一个接口为通过前台传递的用户手机通讯录去匹配也在用这个软件的用户,这些用户都是你通讯录里边的人,你把这些用户返回给前台。当你添加好友时用的就是这些数据,一旦对方同意,你们俩就会成为好友,还有一种方法是根据用户昵称或ID,搜索添加好友。 这些业务逻辑相对都不算太复杂,慢慢尝试就ok。

0 0
原创粉丝点击