21.联系人管理

这篇博客详细介绍了使用Java Web进行联系人管理的实现过程,包括好友申请的完整流程,从客户端查看用户信息,到申请过程,再到添加好友和查询联系人列表的功能。涉及到的关键服务如TanHuaController、MessageService以及FriendApiImpl接口实现类在各步骤中起到了重要作用。
摘要由CSDN通过智能技术生成

联系人管理

  1. 添加好友

    好友申请

    同意并添加好友

  2. 查看好友

一、好友申请流程!

1667262417759

1.1客户端查看感兴趣用户的信息

代码实现

TanHuaController

    /**
     * 好友申请之查看佳人的用户详情:
     * 请求路径:/tanhua/:id/personalInfo
     * 请求方式:get
     * 请求参数:路径参数id,要查看用户详情的那个用户id
     * 响应数据:ToDayBest
     */
    @GetMapping("/{id}/personalInfo")
    public ResponseEntity queryToBestInfo(@PathVariable("id") Long id) {
        TodayBest todayBest = tanHuaService.queryToBestInfo(id);
        return ResponseEntity.ok(todayBest);
    }
TanHuaService
  /**
     * 根据id查看佳人详情
     * 这个id是当前用户要查看的用户的id
     * @param id
     * @return
     */
    public TodayBest queryToBestInfo(Long id) {
        //1.根据用户id查询用户详情
        UserInfo userInfo = userInfoApi.selectUserInfo(id);
        //2.根据当前用户的id,和当前用户要查看的用户id查询推荐人
        RecommendUser recommendUser = recommendUserApi.queryRecommendFriend(id,ThreadLocalUtils.getUserId());
        //3.构造返回值
        TodayBest todayBest = TodayBest.init(userInfo, recommendUser);
        return todayBest;
    }
RecommendUserApiImpl接口实现类
 /**
     * 查看佳人详情
     * @param
     * @param userId
     * @return
     */
    public RecommendUser queryRecommendFriend(Long userId, Long toUserId) {

        Criteria criteria = Criteria.where("userId").is(userId).and("toUserId").is(toUserId);
        Query query = Query.query(criteria);
        RecommendUser recommendUser = mongoTemplate.findOne(query, RecommendUser.class);

        if(recommendUser == null){
            recommendUser = new RecommendUser();
            recommendUser.setUserId(userId);
            recommendUser.setToUserId(toUserId);
            recommendUser.setScore(99d);
        }
        return recommendUser;
    }

1.2点击“聊一下”,获取对方的陌生人问题

TanHUanController

    /**
     * 好友申请之查看佳人详情之后,点击聊一下就可以查看他设置的陌生人问题
     * 请求路径:/tanhua/strangerQuestions
     * 请求方式:get
     * 请求参数:userId,(用户id)
     * 响应数据:String
     */

    @GetMapping("strangerQuestions")
    public ResponseEntity lookStrangerQuestions(Long userId) {
        String strangerQuestions = tanHuaService.lookStrangerQuestions(userId);
        return ResponseEntity.ok(strangerQuestions);
    }
TanHuaService

    /**
     * 根据用户id查看用户设置,陌生人问题
     * @param userId
     * @return
     *
     */
    public String lookStrangerQuestions(Long userId) {
        Question question = questionApi.queryQuestion(userId);
         String strangerQuestions = question == null ?  "请说出石头为什么会这么硬?":question.getTxt();

         return strangerQuestions;
    }
QuestionApiImpl接口实现类

    //根据id查询Question,陌生人问题
    public Question queryQuestion(Long id) {
        QueryWrapper<Question> qw = new QueryWrapper<>();
        qw.eq("user_id", id);
        Question question = questionMapper.selectOne(qw);
        return question;
    }

1.3填写答案,服务端调用环信发送消息到对方手机

TanHuaController
 /**
     * 好友申请之回复陌生人问题:
     * 实现思路:表现层接收参数交由业务层处理
     *        业务层按照约定好的格式构建数据,调用环信服务发送信息
     *
     * 请求路径:/tanhua/strangerQuestions
     * 请求方式:post
     * 请求参数:integer userId(这个是要回复的用户id);string reply(回复的内容),俩者使用map集合接收
     * 响应数据:null
     */
    @PostMapping("/strangerQuestions")
    public ResponseEntity replyStrangerQuestions(@RequestBody Map map){

        //1.接收参数,因为前端传递过来的用户id 是Integer类型,需要转为long类型
        String id = map.get("userId").toString();
        Long userId = Long.valueOf(id);
        String reply = (String) map.get("reply");

        tanHuaService.replyStrangerQuestions(userId,reply);
        return ResponseEntity.ok(null);


   }

TanHuaService
 /**
     * 回复陌生人问题
     * @param userId
     * @param reply
     */
    public void replyStrangerQuestions(Long userId, String reply) {

        //这是发送给感兴趣的用户的信息数据格式
    /**  {
          "userId":1,”        当前操作用户的id
          "huanXinId":“hx1",  操作人的环信用户
           "nickname":"黑马小妹",     niciname:当前操作人昵称
           "strangerQuestion":"你喜欢去看蔚蓝的大海还是去爬巍峨的高山?",
           "reply":"我喜欢秋天的落叶,夏天的泉水,冬天的雪地,只要有你一切皆可~"
           }
     **/
        Long currentId = ThreadLocalUtils.getUserId();
        UserInfo userInfo = userInfoApi.selectUserInfo(currentId);//根据id获取用户详情,再获取用户昵称封装进map集合里

        //思路:构造一个map集合封装起来,再用工具转为JSON格式
        //1.构造数据
        Map map = new HashMap();
        map.put("userId", currentId);
        map.put("huanXinId", Constants. HX_USER_PREFIX+ currentId);
        map.put("nickname",userInfo.getNickname());
        map.put("strangerQuestion",lookStrangerQuestions(userId));//对方设置的问题
        map.put("reply",reply);//当前用户回答的问题
        //2.转为json
        String replyText = JSON.toJSONString(map);

        //3.调用环信服务回复陌生人问题,这是服务器操作java代码回复用户的
        //俩个参数,一个是要回复的对方环信id;另一个是要回复的内容
        Boolean result = huanXinTemplate.sendMsg(Constants.HX_USER_PREFIX + userId, replyText);
        if(!result ){
            throw new BusinessException(ErrorResult.error());
        }


    }

二、添加好友

表结构:

1667263957822

实现思路:

1667264155762

代码实现:

MessagesController


    /*
     * 点击确认添加之后,添加好友:
     * 请求路径:/messages/contacts
     * 请求方式:post
     * 请求参数:要添加的好友的用户id,  integer   userId,使用map集合接收
     * 响应数据:null
     */

    @PostMapping("/contacts")
    public ResponseEntity addFriend(@RequestBody Map map){
        String id = map.get("userId").toString();
        Long friendId = Long.valueOf(id);

        messagesService.addFriend(friendId);

        return ResponseEntity.ok(null);
    }

MessageService

 /**
     *添加联系人
     * @param friendId
     */
    public void addFriend(Long friendId) {
        //1.把好友关系注册到环信
        Long userId = ThreadLocalUtils.getUserId();
        //俩个参数,一个是当前用户的环信id,一个是对方账号的环信id
        Boolean result = huanXinTemplate.addContact(Constants.HX_USER_PREFIX + userId, Constants.HX_USER_PREFIX + friendId);
        if(!result){
            throw new BusinessException(ErrorResult.error());
        }
        //2.把好友关系数据保存到自己的数据库
        friendApi.save(userId,friendId);
    }

FriendApiImpl

  @Override
    public void save(Long userId, Long friendId) {

        //站在我的角度,保存一份好友数据
        //站在好友的角度,也要保存数据一分
        //1.判断好友关系数据库中是否已经存在
        Criteria criteria = Criteria.where("userId").is(userId).and("friendId").is(friendId);
        Query query = Query.query(criteria);
        boolean result = mongoTemplate.exists(query, Friend.class);

        if(!result){

            Friend friend = new Friend();
            friend.setUserId(userId);
            friend.setFriendId(friendId);
            friend.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend);
        }

        Criteria criteria1 = Criteria.where("friendId").is(userId).and("userId").is(friendId);
        Query query1 = Query.query(criteria1);
        boolean exists1 = mongoTemplate.exists(query1, Friend.class);
        if (!exists1){
            Friend friend2 = new Friend();
            friend2.setUserId(friendId);
            friend2.setFriendId(userId);
            friend2.setCreated(System.currentTimeMillis());
            mongoTemplate.save(friend2);
        }

    }

三、查询联系人列表

1667264609300

代码实现

MessagesController

/**
     * 分页查询好友列表:
     * 请求路径:/messages/contacts
     * 请求方式:get
     * 请求参数:     Integer page(当前页码),Integer pageSize(每页展示数),String keyword(关键字)
     *响应数据:ContactVo
     */
    @GetMapping("/contacts")
    public ResponseEntity queryFriends(@RequestParam(defaultValue = "1") Integer page,
                                       @RequestParam(defaultValue = "10") Integer pageSize,
                                       String keyword){

        PageResult pageResult = messagesService.queryFriends(page,pageSize,keyword);
        return ResponseEntity.ok(pageResult);

MessageService

/**
     * 分页查询练习人
     * @param page
     * @param pageSize
     * @param keyword
     * @return
     */
    public PageResult queryFriends(Integer page, Integer pageSize, String keyword) {
        //1.分页查询当前用户的好友集合
        Long currentId = ThreadLocalUtils.getUserId();
        List<Friend> friends = friendApi.queryFriends(currentId,page,pageSize);

        //2.判断当前用户是否有好友,没有就new一个PageResult返回
        if(CollUtil.isEmpty(friends)){
           return new PageResult();
        }

        //3.批量获取好友的id,再根据id查询好友的详情
        List<Long> friendIds = CollUtil.getFieldValues(friends, "friendId", Long.class);
        //添加查询的条件,根据关键字查询
        UserInfo userInfo = new UserInfo();
        userInfo.setNickname(keyword);
        Map<Long, UserInfo> userInfoMap = userInfoApi.batchQueryUserInfo(friendIds, userInfo);


        //4.遍历好友集合,没遍历一个好友就构造一个vo对象
        List<ContactVo> contactVos = new ArrayList<>();
        for (Friend friend : friends) {

            Long friendId = friend.getFriendId();
            UserInfo userInfo1 = userInfoMap.get(friendId);

            if(userInfo1 != null){
                ContactVo contactVo = ContactVo.init(userInfo1);
                contactVos.add(contactVo);
            }

        }

        //5.构造返回值
        PageResult pageResult = new PageResult(page,pageSize,0,contactVos);
        return pageResult;

    }

FriendApiImpl接口实现类

/**
     * 分页查询好友
     * @param currentId
     * @param page
     * @param pageSize
     * @return
     */
    public List<Friend> queryFriends(Long currentId, Integer page, Integer pageSize) {
        Criteria criteria = Criteria.where("userId").is(currentId);
        Query query = Query.query(criteria);
        query.skip((page - 1 ) * pageSize).limit(pageSize).with(Sort.by(Sort.Order.desc("created")));

        List<Friend> friends = mongoTemplate.find(query, Friend.class);
        return friends;

    }

queryFriends(Long currentId, Integer page, Integer pageSize) {
Criteria criteria = Criteria.where(“userId”).is(currentId);
Query query = Query.query(criteria);
query.skip((page - 1 ) * pageSize).limit(pageSize).with(Sort.by(Sort.Order.desc(“created”)));

    List<Friend> friends = mongoTemplate.find(query, Friend.class);
    return friends;

}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

糖分你俩颗~~~

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值