rabbitmq实现用户关系绑定信息推送

1.MQ三大要点

  1. 交换机
  2. 队列
  3. Key

2.交换机

  交换机是消息队列系统中的一个核心组件,主要用于将消息路由到一个或多个队列中。交换机通过不同的路由规则来决定消息的去向。根据不同的类型,交换机可以有不同的路由策略:
  • 直连交换机(Direct Exchange):根据消息的路由键(Routing Key)将消息路由到一个或多个队列。
  • 主题交换机(Topic Exchange):根据主题模式(Routing Key 的模式匹配)来路由消息,支持更灵活的路由规则。
  • 扇出交换机(Fanout Exchange):将消息广播到所有绑定的队列,不考虑路由键。
  • 匹配交换机(Headers Exchange):基于消息的头部属性进行路由,而不是路由键。

3.队列(Queue)

  队列是消息存储的地方,也是消息传递的核心部分。消息生产者将消息发送到交换机,交换机根据路由规则将消息转发到一个或多个队列中。消费者从队列中取出消息进行处理。队列通常有以下特性:
  • 持久性:消息队列可以配置为持久的,确保在系统重启后消息不会丢失。
  • 优先级:一些队列支持消息的优先级设置,以决定哪些消息优先被处理。
  • 延迟:队列可以设置延迟时间,让消息在一定时间后才被处理。

4.Key(路由键)

  路由键是用于交换机将消息路由到特定队列的重要标识。不同类型的交换机使用路由键的方式有所不同:
  • 直连交换机:路由键完全匹配队列的绑定键(Binding Key)来路由消息。
  • 主题交换机:路由键可以使用通配符进行模式匹配,使得消息可以根据路由键的模式被发送到多个队列。
  • 扇出交换机:不使用路由键,因为所有绑定的队列都接收消息。
  • 匹配交换机:基于消息的头部信息进行匹配,不依赖路由键。

5.java如何使用?

  1. FANOUT模式
     
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "BLUE_QUEUE_ONE"),
            exchange = @Exchange(name = "BLUE_FANOUT",type = ExchangeTypes.FANOUT)
    ))
    public void listenerOne(Map map){
        log.info("队列一监听到map:{}",map);
    }
  2. Direct 模式
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = "BLUE_QUEUE_THREE"),
            exchange = @Exchange(name = "BLUE_DIRECT",type = ExchangeTypes.DIRECT),
            key = "ABC"
    ))
    public void listenerThree(Map map){
        log.info("队列三监听到map:{}",map);
    }

在用户关系绑定当中,关注,拉黑,取关这些操作如果碰上处理较慢时,给用户带来的使用体验便不是很好,我们选择引入消息中间件rabbitmq,当消息传入时,便进行回馈反映

查询关联关系接口

package com.litblue.user.service.impl;

import com.litblue.api.client.GetArtWorkClient;
import com.litblue.common.utils.UserContext;
import com.litblue.starter.core.AjaxResult;
import com.litblue.starter.pojo.artwork.query.LitArtworkInfoQuery;
import com.litblue.starter.pojo.user.domian.LitUserInfo;
import com.litblue.starter.pojo.user.vo.LitHomeUserDataVo;
import com.litblue.user.service.ILitUserRelationService;
import com.litblue.user.service.IPersonInfoService;
import lombok.AllArgsConstructor;
import org.springframework.stereotype.Service;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service
@AllArgsConstructor
public class PersonInfoServiceImpl implements IPersonInfoService {


    private final GetArtWorkClient artWorkClient;

    private final LitUserRelationServiceImpl userRelationService;

    /**
     * 查询个人中心数据
     *
     * @return
     */
    @Override
    public Map<String, Object> searchPersonHomeData(String userId) {
        // 查询获赞数据
        LitArtworkInfoQuery litArtworkInfoQuery = new LitArtworkInfoQuery();
        litArtworkInfoQuery.setUserId(userId);
        Integer homeLikeNums = artWorkClient.queryUserHomeData(litArtworkInfoQuery);
//
//        // 查询互相关注
        List<LitHomeUserDataVo> withFocus = userRelationService.getMyFriends(userId);
//        List<LitHomeUserDataVo> withFocus = userRelationService.getFocusData(userId, "FRIEND_FOCUS");
//        // 查询我的关注
        List<LitHomeUserDataVo> meFocus = userRelationService.getMeFocus(userId);
//        List<LitHomeUserDataVo> meFocus = userRelationService.getFocusData(userId, "ME_FOCUS");
//       // 查询关注我的
        List<LitHomeUserDataVo> focusMe = userRelationService.getFocusMe(userId);

        HashMap<String, Object> map = new HashMap<>();
        map.put("homeLikeNums", formatNumber(homeLikeNums));
        map.put("withFocusPersons", withFocus);
        map.put("withFocusNums", formatNumber(withFocus.size()));
        map.put("meFocusPersons", meFocus);
        map.put("meFocusNums", formatNumber(meFocus.size()));
        map.put("focusMePersons", focusMe);
        map.put("focusMeNums", formatNumber(focusMe.size()));

        return map;
    }

    /**
     * 格式化数字为多少多少w的格式
     *
     * @param number 需要格式化的数字
     * @return 格式化后的字符串
     */
    private String formatNumber(int number) {
        if (number >= 10000) {
            return (number / 10000) + "w";
        } else {
            return String.valueOf(number);
        }
    }

}
package com.litblue.user.service.impl;

import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.litblue.common.utils.UserContext;
import com.litblue.starter.cache.redis.RedisCache;
import com.litblue.starter.cache.redis.RedisKeys;
import com.litblue.starter.core.AjaxResult;
import com.litblue.starter.mq.rabbit.MqExChanges.MqExChangeUserRelationInterProperties;
import com.litblue.starter.pojo.user.domian.LitUserInfo;
import com.litblue.starter.pojo.user.domian.LitUserRelation;
import com.litblue.starter.pojo.user.dto.RelationChoose;
import com.litblue.starter.pojo.user.vo.LitHomeUserDataVo;
import com.litblue.user.factory.RelationFactory;
import com.litblue.user.mapper.LitUserRelationMapper;
import com.litblue.user.service.ILitUserInfoService;
import com.litblue.user.service.ILitUserRelationService;
import com.litblue.user.service.ILitVisitorRecordingService;
import lombok.AllArgsConstructor;
import org.springframework.amqp.rabbit.core.RabbitTemplate;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.util.*;
import java.util.concurrent.TimeUnit;


@Service

public class LitUserRelationServiceImpl extends ServiceImpl<LitUserRelationMapper, LitUserRelation> implements ILitUserRelationService {
    @Autowired
    private RedisCache redisCache;
    @Autowired
    private RabbitTemplate rabbitTemplate;

    @Lazy
    @Autowired
    private ILitVisitorRecordingService visitorRecordingService;

    @Autowired
    private ILitUserInfoService userInfoService;

    /**
     * 绑定用户关系
     *
     * @param litUserRelation
     * @return
     */
    @Override
    public AjaxResult bindRelation(LitUserRelation litUserRelation) {
        String applyUserId = String.valueOf(litUserRelation.getApplyUserId());
        String beAppliedUserId = String.valueOf(litUserRelation.getTargetUserId());
        String relationType = litUserRelation.getRelationType();
        switch (relationType) {
            case "0": // 关注
                handleRelation(applyUserId, beAppliedUserId, "FOCUS", litUserRelation,
                        MqExChangeUserRelationInterProperties.ROUTING_RELATION_KEY_FOCUS);
                break;
            case "1": // 拉黑
                //移除关注关系
                removeRelation(applyUserId, beAppliedUserId, "FOCUS");
                handleRelation(applyUserId, beAppliedUserId, "LOCK", litUserRelation,
                        MqExChangeUserRelationInterProperties.ROUTING_RELATION_KEY_LOCK);
                this.redisCache.deleteKeysByPattern(RedisKeys.LIT_ALL_ARTWORK_VOS_KEY);
                break;
            case "2": // 取消关注
                //移除关注关系
                removeRelation(applyUserId, beAppliedUserId, "FOCUS");
                updateVisitorRecords(beAppliedUserId, applyUserId, litUserRelation.getTypeName(), "2");
                sendMessage(litUserRelation, MqExChangeUserRelationInterProperties.ROUTING_RELATION_KEY_UN_FOCUS);
                break;
            case "3": // 移除拉黑
                //移除关注关系
                removeRelation(applyUserId, beAppliedUserId, "LOCK");
                sendMessage(litUserRelation, MqExChangeUserRelationInterProperties.ROUTING_RELATION_KEY_UN_LOCK);
                this.redisCache.deleteKeysByPattern(RedisKeys.LIT_ALL_ARTWORK_VOS_KEY);
                break;
            default:
                return new AjaxResult("无效的关系类型", "500");
        }

        return new AjaxResult("操作成功", "200");
    }

    /**
     * 绑定关注关系
     *
     * @param applyUserId
     * @param beAppliedUserId
     * @param keyPrefix
     * @param litUserRelation
     * @param routingKey
     */
    private void handleRelation(String applyUserId, String beAppliedUserId, String keyPrefix, LitUserRelation litUserRelation,
                                String routingKey) {
        RedisKeys redisKeys = RedisKeys.forBingUserRelation(applyUserId, beAppliedUserId, keyPrefix);
        this.redisCache.setCacheObject(redisKeys.BIND_USER_REL_KEY, litUserRelation);
        updateVisitorRecords(beAppliedUserId, applyUserId, litUserRelation.getTypeName(), "0");
        sendMessage(litUserRelation, routingKey);
    }

    /**
     * 移除用户关注关系
     *
     * @param applyUserId
     * @param beAppliedUserId
     * @param keyPrefix
     */
    private void removeRelation(String applyUserId, String beAppliedUserId, String keyPrefix) {
        RedisKeys redisKeys = RedisKeys.forBingUserRelation(applyUserId, beAppliedUserId, keyPrefix);
        LitUserRelation existingRelation = this.redisCache.getCacheObject(redisKeys.BIND_USER_REL_KEY);
        if (existingRelation != null) {
            this.redisCache.deleteObject(redisKeys.BIND_USER_REL_KEY);
        }
    }

    /**
     * 更新访客状态
     *
     * @param beAppliedUserId
     * @param applyUserId
     * @param typeName
     * @param isLoginCurrentUser
     */
    private void updateVisitorRecords(String beAppliedUserId, String applyUserId,
                                      String typeName, String isLoginCurrentUser) {
        AjaxResult ajaxResult = this.visitorRecordingService.queryVisitorRecords();
        if (ajaxResult != null && ajaxResult.getData() != null) {
            List<LitHomeUserDataVo> litVisitorVos = (List<LitHomeUserDataVo>) ajaxResult.getData();
            for (LitHomeUserDataVo litVisitorVo : litVisitorVos) {
                if (String.valueOf(litVisitorVo.getLitUserInfo().getId()).equals(beAppliedUserId)) {
                    RedisKeys editKey = RedisKeys.forVisitor(applyUserId, beAppliedUserId);
                    this.redisCache.deleteObject(editKey.VISITOR_KEY);
                    litVisitorVo.setEditName(typeName);
                    litVisitorVo.setIsLoginCurrentUser(isLoginCurrentUser);
                    HashMap<String, Object> map = new HashMap<>();
                    map.put("loginId", Long.valueOf(beAppliedUserId));
                    map.put("isLoginCurrentUser", isLoginCurrentUser);
                    this.redisCache.setCacheObject(editKey.VISITOR_KEY, map, 30, TimeUnit.DAYS);
                }
            }
        }
    }

    /**
     * 异步落库
     *
     * @param litUserRelation
     * @param routingKey
     */
    private void sendMessage(LitUserRelation litUserRelation, String routingKey) {
        rabbitTemplate.convertAndSend(MqExChangeUserRelationInterProperties.DIRECT_RELATION, routingKey, litUserRelation);
    }


    /**
     * 获取对方用户和登录人的关系(双向)
     *
     * @param hisId   对方用户ID
     * @param loginId 登录用户ID
     * @return AjaxResult 包含关系状态的信息
     */
    @Override
    public AjaxResult queryHisRelationWithMe(String hisId, String loginId) {
        //获取我和他的关系
        String relationKeyPrefix1 = "bind:" + loginId + ":" + hisId + "*";
        //获取他和我的关系
        String relationKeyPrefix2 = "bind:" + hisId + ":" + loginId + "*";

        String relationType1 = getRelationType(relationKeyPrefix1);
        String relationType2 = getRelationType(relationKeyPrefix2);
        //获取策略
        RelationFactory relationFactory = new RelationFactory(relationType1, relationType2);
        Map<String, Object> strategy = relationFactory.findStrategy();

        return new AjaxResult("查询成功", "200", strategy);
    }

    /**
     * 获取我的用户状态
     *
     * @param keyPrefix
     * @return
     */
    @Override
    public AjaxResult fetchUserRelationGroup(String keyPrefix) {
//        if ()
        return null;
    }


//    public List<LitHomeUserDataVo> getFocusData(String userId, String type) {
//        List focusData = new ArrayList<LitHomeUserDataVo>();
//        String focusDataKey = null;
//        Long relationUserId = null;
//        if ("ME_FOCUS".equals(type)) {
//            focusDataKey = "bind:" + userId + ":*:FOCUS";
//        }
//        if ("FRIEND_FOCUS".equals(type)) {
//            focusDataKey = "bind:*:" + userId + ":FOCUS";
//        }
//        if ("FOCUS_ME".equals(type)) {
//            focusDataKey = "bind:" + "*" + ":" + userId + "*" + "FOCUS";
//        }
//        Set<String> keys = this.redisCache.redisTemplate.keys(focusDataKey);
//        for (String key : keys) {
//            //拿到他的信息
//            LitUserRelation litUserRelation = this.redisCache.getCacheObject(key);
//            if ("ME_FOCUS".equals(type)) {
//                relationUserId = litUserRelation.getTargetUserId();
//            }
//            if ("FOCUS_ME".equals(type) || "FRIEND_FOCUS".equals(type)) {
//                relationUserId = litUserRelation.getApplyUserId();
//            }
//            AjaxResult ajaxResult = this.queryHisRelationWithMe(String.valueOf(relationUserId), String.valueOf(userId));
//            Map res = (Map) ajaxResult.getData();
//            LitUserInfo litUserInfo = this.userInfoService.queryUserInfo(relationUserId);
//            LitHomeUserDataVo litHomeUserDataVo = new LitHomeUserDataVo();
//            litHomeUserDataVo.setIsLoginCurrentUser(res.get("isLoginCurrentUser").toString());
//            litHomeUserDataVo.setEditName(res.get("editName").toString());
//            litHomeUserDataVo.setRelationChooseList((List<RelationChoose>) res.get("relationChooses"));
//            litHomeUserDataVo.setLitUserInfo(litUserInfo);
//            focusData.add(litHomeUserDataVo);
//        }
//        return focusData;
//    }

    public List<LitHomeUserDataVo> getFocusData(String userId, String type) {
        List<LitHomeUserDataVo> focusData = new ArrayList<>();
        String keyPattern = null;

        switch (type) {
            case "meFocus":
                keyPattern = "bind:" + userId + ":*:FOCUS";
                break;
            case "focusMe":
                keyPattern = "bind:*:" + userId + ":FOCUS";
                break;
            case "myFriends":
                keyPattern = "bind:*:" + userId + ":FOCUS";
                break;
            default:
                throw new IllegalArgumentException("Invalid type: " + type);
        }

        Set<String> keys = this.redisCache.redisTemplate.keys(keyPattern);
        for (String key : keys) {
            LitUserRelation litUserRelation = this.redisCache.getCacheObject(key);
            Long otherUserId = type.equals("focusMe") ? litUserRelation.getApplyUserId() : litUserRelation.getTargetUserId();
            LitUserInfo litUserInfo = this.userInfoService.queryUserInfo(otherUserId);
            AjaxResult ajaxResult = this.queryHisRelationWithMe(String.valueOf(otherUserId), String.valueOf(userId));
            Map res = (Map) ajaxResult.getData();

            LitHomeUserDataVo litHomeUserDataVo = new LitHomeUserDataVo();
            litHomeUserDataVo.setIsLoginCurrentUser(res.get("isLoginCurrentUser").toString());
            litHomeUserDataVo.setEditName(res.get("editName").toString());
            litHomeUserDataVo.setRelationChooseList((List<RelationChoose>) res.get("relationChooses"));
            litHomeUserDataVo.setLitUserInfo(litUserInfo);

            if ("myFriends".equals(type) && !"互相关注".equals(res.get("editName").toString())) {
                continue;
            }

            focusData.add(litHomeUserDataVo);
        }

        return focusData;
    }

    /**
     * 获取我关注的
     *
     * @return
     */
    @Override
    public List<LitHomeUserDataVo> getMeFocus(String userId) {
        List meFocus = new ArrayList<LitHomeUserDataVo>();
        String ME_FOCUS_KEY = "bind:" + userId + ":*:FOCUS";
        Set<String> keys = this.redisCache.redisTemplate.keys(ME_FOCUS_KEY);
        for (String key : keys) {
            //拿到他的信息
            LitUserRelation litUserRelation = this.redisCache.getCacheObject(key);
            Long targetUserId = litUserRelation.getTargetUserId();
            LitUserInfo litUserInfo = this.userInfoService.queryUserInfo(targetUserId);
            AjaxResult ajaxResult = this.queryHisRelationWithMe(String.valueOf(targetUserId), String.valueOf(userId));
            Map res = (Map) ajaxResult.getData();
            LitHomeUserDataVo litHomeUserDataVo = new LitHomeUserDataVo();
            litHomeUserDataVo.setIsLoginCurrentUser(res.get("isLoginCurrentUser").toString());
            litHomeUserDataVo.setEditName(res.get("editName").toString());
            litHomeUserDataVo.setRelationChooseList((List<RelationChoose>) res.get("relationChooses"));
            litHomeUserDataVo.setLitUserInfo(litUserInfo);
            meFocus.add(litHomeUserDataVo);
        }
        return meFocus;
    }


    /**
     * 获取关注我的
     *
     * @return
     */
    public List<LitHomeUserDataVo> getFocusMe(String userId) {
        List focusMe = new ArrayList<LitHomeUserDataVo>();
        String FOCUS_ME_KEY = "bind:" + "*" + ":" + userId + "*" + "FOCUS";
        Set<String> keys = this.redisCache.redisTemplate.keys(FOCUS_ME_KEY);
        for (String key : keys) {
            //拿到他的信息
            LitUserRelation litUserRelation = this.redisCache.getCacheObject(key);
            Long applyUserId = litUserRelation.getApplyUserId();
            LitUserInfo litUserInfo = this.userInfoService.queryUserInfo(applyUserId);
            AjaxResult ajaxResult = this.queryHisRelationWithMe(String.valueOf(applyUserId), String.valueOf(userId));
            Map res = (Map) ajaxResult.getData();
            LitHomeUserDataVo litHomeUserDataVo = new LitHomeUserDataVo();
            litHomeUserDataVo.setIsLoginCurrentUser(res.get("isLoginCurrentUser").toString());
            litHomeUserDataVo.setEditName(res.get("editName").toString());
            litHomeUserDataVo.setRelationChooseList((List<RelationChoose>) res.get("relationChooses"));
            litHomeUserDataVo.setLitUserInfo(litUserInfo);
            focusMe.add(litHomeUserDataVo);
        }
        return focusMe;
    }


    @Override
    public List<LitHomeUserDataVo> getMyFriends(String userId) {
        List<LitHomeUserDataVo> myFriends = new ArrayList<>();
        // 设置 friendsKey
        String friendsKey = "bind:*:" + userId + ":FOCUS";
        // 获取 Redis 中的 key 集合
        Set<String> keys = this.redisCache.redisTemplate.keys(friendsKey);
        // 根据不同的 type 处理逻辑
        for (String key : keys) {
            LitUserRelation litUserRelation = this.redisCache.getCacheObject(key);
            Long applyUserId = litUserRelation.getApplyUserId();
            AjaxResult ajaxResult = this.queryHisRelationWithMe(String.valueOf(applyUserId), String.valueOf(userId));
            Map res = (Map) ajaxResult.getData();
            String editName = res.get("editName").toString();
            LitHomeUserDataVo litHomeUserDataVo = new LitHomeUserDataVo();
            litHomeUserDataVo.setIsLoginCurrentUser(res.get("isLoginCurrentUser").toString());
            litHomeUserDataVo.setEditName(editName);
            litHomeUserDataVo.setRelationChooseList((List<RelationChoose>) res.get("relationChooses"));
            // 处理互相关注
            if ("互相关注".equals(editName)) {
                LitUserInfo litUserInfo = this.userInfoService.queryUserInfo(applyUserId);
                litHomeUserDataVo.setLitUserInfo(litUserInfo);
                myFriends.add(litHomeUserDataVo);
            }
        }
        return myFriends;
    }

    /**
     * 根据关系键前缀查询关系类型
     *
     * @param relationKeyPrefix 关系键前缀
     * @return 关系类型字符串
     */
    private String getRelationType(String relationKeyPrefix) {
        Set<String> keys = null;
        try {
            keys = this.redisCache.redisTemplate.keys(relationKeyPrefix);
        } catch (Exception e) {
            return "2"; // Redis 操作异常,默认为尚未关注
        }
        String relationType = "2"; // 默认状态为尚未关注
        if (!CollectionUtils.isEmpty(keys)) {
            for (String key : keys) {
                LitUserRelation relation = this.redisCache.getCacheObject(key);
                if (relation != null) {
                    relationType = relation.getRelationType();
                    break; // 假设每个用户关系只有一个存储在 Redis 中,找到一个即可跳出循环
                }
            }
        }
        return relationType;
    }
}

mq配置类

package com.litblue.starter.pojo.user.domian;

import com.baomidou.mybatisplus.annotation.FieldFill;
import com.baomidou.mybatisplus.annotation.TableField;
import com.litblue.starter.core.BaseEntity;
import lombok.Data;

import java.util.Date;

/**
 * 用户关系
 */
@Data

public class LitUserRelation extends BaseEntity {


    /**
     * 主键
     */
    private Long id;
    /**
     * 发起用户id
     */
    private Long applyUserId;
    /**
     * 目标用户id
     */
    private Long targetUserId;
    /**
     * 关系状态(0 关注 1 拉黑 2 取消关注 3 移除拉黑)
     */
    private String relationType;
    /**
     * 状态名称
     */
    private String typeName;

    /**
     * 数据状态 1-正常 2-删除
     */
    @TableField(fill = FieldFill.INSERT)
    private Integer deleteStatus;

}

关键key

package com.litblue.starter.mq.rabbit.MqExChanges;

/**
 * 用户关系队列
 */
public interface MqExChangeUserRelationInterProperties {

    //用户关系交换机
    public static final String DIRECT_RELATION = "relation.direct";

    //用户关注操作队列
    public static final String QUEUE_RELATION_FOCUS = "queue.relation.focus";

    //用户拉黑操作队列
    public static final String QUEUE_RELATION_LOCK = "queue.relation.lock";

    //用户取消关注操作队列
    public static final String QUEUE_RELATION_UN_FOCUS = "queue.relation.unfocus";

    //用户移除拉黑操作队列
    public static final String QUEUE_RELATION_UN_LOCK = "queue.relation.unlock";


    //用户关注key
    public static final String ROUTING_RELATION_KEY_FOCUS = "relation.focus";


    //用户拉黑key
    public static final String ROUTING_RELATION_KEY_LOCK = "relation.lock";


    //用户取消关注key
    public static final String ROUTING_RELATION_KEY_UN_FOCUS = "relation.unfocus";


    //用户移除拉黑key
    public static final String ROUTING_RELATION_KEY_UN_LOCK = "relation.unlock";
}
package com.litblue.user.listener;


import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.litblue.starter.mq.rabbit.MqExChanges.MqExChangeArtWorkInterProperties;
import com.litblue.starter.mq.rabbit.MqExChanges.MqExChangeUserRelationInterProperties;
import com.litblue.starter.pojo.artwork.dto.LitArtworkUserDto;
import com.litblue.starter.pojo.user.domian.LitUserRelation;
import com.litblue.user.mapper.LitUserRelationMapper;
import lombok.RequiredArgsConstructor;
import org.springframework.amqp.core.ExchangeTypes;
import org.springframework.amqp.rabbit.annotation.Exchange;
import org.springframework.amqp.rabbit.annotation.Queue;
import org.springframework.amqp.rabbit.annotation.QueueBinding;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;


/**
 * 用户关系状态监听
 */
@Component
@RequiredArgsConstructor
public class LitUserRelationListener {

    private final LitUserRelationMapper litUserRelationMapper;

    /**
     * 监听用户关注操作
     *
     * @param litUserRelation
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqExChangeUserRelationInterProperties.QUEUE_RELATION_FOCUS),
            exchange = @Exchange(name = MqExChangeUserRelationInterProperties.DIRECT_RELATION, type = ExchangeTypes.DIRECT),
            key = MqExChangeUserRelationInterProperties.ROUTING_RELATION_KEY_FOCUS
    ))
    public void listenRelationFocus(LitUserRelation litUserRelation) {
        this.litUserRelationMapper.insert(litUserRelation);
    }


    /**
     * 监听用户拉黑操作
     *
     * @param litUserRelation
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqExChangeUserRelationInterProperties.QUEUE_RELATION_LOCK),
            exchange = @Exchange(name = MqExChangeUserRelationInterProperties.DIRECT_RELATION, type = ExchangeTypes.DIRECT),
            key = MqExChangeUserRelationInterProperties.ROUTING_RELATION_KEY_LOCK
    ))
    public void listenRelationLock(LitUserRelation litUserRelation) {
        LambdaQueryWrapper<LitUserRelation> litUserRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        litUserRelationLambdaQueryWrapper.eq(LitUserRelation::getApplyUserId, litUserRelation.getApplyUserId());
        litUserRelationLambdaQueryWrapper.eq(LitUserRelation::getTargetUserId, litUserRelation.getTargetUserId());
        litUserRelationLambdaQueryWrapper.eq(LitUserRelation::getRelationType, 0);
        LitUserRelation relation = this.litUserRelationMapper.selectOne(litUserRelationLambdaQueryWrapper);
        if (relation != null) {
            //移除好友关注关系
            this.litUserRelationMapper.removeRelation(relation);
        }
        //设置拉黑状态
        this.litUserRelationMapper.insert(litUserRelation);
    }


    /**
     * 监听用户取消关注操作
     *
     * @param litUserRelation
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqExChangeUserRelationInterProperties.QUEUE_RELATION_UN_FOCUS),
            exchange = @Exchange(name = MqExChangeUserRelationInterProperties.DIRECT_RELATION, type = ExchangeTypes.DIRECT),
            key = MqExChangeUserRelationInterProperties.ROUTING_RELATION_KEY_UN_FOCUS
    ))
    public void listenRelationUnFocus(LitUserRelation litUserRelation) {
        LambdaQueryWrapper<LitUserRelation> litUserRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        litUserRelationLambdaQueryWrapper.eq(LitUserRelation::getApplyUserId, litUserRelation.getApplyUserId());
        litUserRelationLambdaQueryWrapper.eq(LitUserRelation::getTargetUserId, litUserRelation.getTargetUserId());
        litUserRelationLambdaQueryWrapper.eq(LitUserRelation::getRelationType, 0);
        LitUserRelation relation = this.litUserRelationMapper.selectOne(litUserRelationLambdaQueryWrapper);
        if (relation != null) {
            this.litUserRelationMapper.removeRelation(relation);
        }
    }


    /**
     * 监听用户移除拉黑操作
     *
     * @param litUserRelation
     */
    @RabbitListener(bindings = @QueueBinding(
            value = @Queue(name = MqExChangeUserRelationInterProperties.QUEUE_RELATION_UN_LOCK),
            exchange = @Exchange(name = MqExChangeUserRelationInterProperties.DIRECT_RELATION, type = ExchangeTypes.DIRECT),
            key = MqExChangeUserRelationInterProperties.ROUTING_RELATION_KEY_UN_LOCK
    ))
    public void listenRelationUnLock(LitUserRelation litUserRelation) {
        LambdaQueryWrapper<LitUserRelation> litUserRelationLambdaQueryWrapper = new LambdaQueryWrapper<>();
        litUserRelationLambdaQueryWrapper.eq(LitUserRelation::getApplyUserId, litUserRelation.getApplyUserId());
        litUserRelationLambdaQueryWrapper.eq(LitUserRelation::getTargetUserId, litUserRelation.getTargetUserId());
        litUserRelationLambdaQueryWrapper.eq(LitUserRelation::getRelationType, 3);
        LitUserRelation relation = this.litUserRelationMapper.selectOne(litUserRelationLambdaQueryWrapper);
        if (relation != null) {
            this.litUserRelationMapper.removeRelation(relation);
        }
    }
}

好友策略工厂及实现方法

package com.litblue.user.factory;

import java.util.HashMap;
import java.util.Map;

/**
 * 好友策略工厂
 */
public class RelationFactory {

    private String[] relationShipArr;

    public RelationFactory(String relationType1, String relationType2) {
        this.relationShipArr = new String[]{relationType1, relationType2};
    }

    /**
     * 查找策略并执行
     * @return 执行结果
     */
    public Map<String, Object> findStrategy() {
        // 初始化结果
        Map<String, Object> result = new HashMap<>();

        // 根据传入的关系类型数组选择策略
        if ("0".equals(relationShipArr[0]) && "0".equals(relationShipArr[1])) {
            // 0, 0 对应的策略
            RelationStrategy strategy = new StrategyAll.FirstStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("0".equals(relationShipArr[0]) && "1".equals(relationShipArr[1])) {
            // 0, 1 对应的策略
            RelationStrategy strategy = new StrategyAll.SecondStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("0".equals(relationShipArr[0]) && "2".equals(relationShipArr[1])) {
            // 0, 2 对应的策略
            RelationStrategy strategy = new StrategyAll.ThirdStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("0".equals(relationShipArr[0]) && "3".equals(relationShipArr[1])) {
            // 0, 3 对应的策略
            RelationStrategy strategy = new StrategyAll.FourthStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("1".equals(relationShipArr[0]) && "0".equals(relationShipArr[1])) {
            // 1, 0 对应的策略
            RelationStrategy strategy = new StrategyAll.FifthStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("1".equals(relationShipArr[0]) && "1".equals(relationShipArr[1])) {
            // 1, 1 对应的策略
            RelationStrategy strategy = new StrategyAll.SixthStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("1".equals(relationShipArr[0]) && "2".equals(relationShipArr[1])) {
            // 1, 2 对应的策略
            RelationStrategy strategy = new StrategyAll.SeventhStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("1".equals(relationShipArr[0]) && "3".equals(relationShipArr[1])) {
            // 1, 3 对应的策略
            RelationStrategy strategy = new StrategyAll.EighthStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("2".equals(relationShipArr[0]) && "0".equals(relationShipArr[1])) {
            // 2, 0 对应的策略
            RelationStrategy strategy = new StrategyAll.NinthStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("2".equals(relationShipArr[0]) && "1".equals(relationShipArr[1])) {
            // 2, 1 对应的策略
            RelationStrategy strategy = new StrategyAll.TenthStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("2".equals(relationShipArr[0]) && "2".equals(relationShipArr[1])) {
            // 2, 2 对应的策略
            RelationStrategy strategy = new StrategyAll.EleventhStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("2".equals(relationShipArr[0]) && "3".equals(relationShipArr[1])) {
            // 2, 3 对应的策略
            RelationStrategy strategy = new StrategyAll.TwelfthStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("3".equals(relationShipArr[0]) && "0".equals(relationShipArr[1])) {
            // 3, 0 对应的策略
            RelationStrategy strategy = new StrategyAll.ThirteenthStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("3".equals(relationShipArr[0]) && "1".equals(relationShipArr[1])) {
            // 3, 1 对应的策略
            RelationStrategy strategy = new StrategyAll.FourteenthStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("3".equals(relationShipArr[0]) && "2".equals(relationShipArr[1])) {
            // 3, 2 对应的策略
            RelationStrategy strategy = new StrategyAll.FifteenthStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        } else if ("3".equals(relationShipArr[0]) && "3".equals(relationShipArr[1])) {
            // 3, 3 对应的策略
            RelationStrategy strategy = new StrategyAll.SixteenthStrategy();
            result = strategy.combineRelationTypes(relationShipArr[0], relationShipArr[1]);
        }
        return result;
    }
}
package com.litblue.user.factory;

import java.util.Map;

public interface RelationStrategy {
    Map<String, Object> combineRelationTypes(String relationType1, String relationType2);
}
package com.litblue.user.factory;

import com.litblue.starter.pojo.user.dto.RelationChoose;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * (0 关注 1 拉黑 2 取消关注 3 移除拉黑)
 */
public class StrategyAll {

    private static Map<String, Object> editChoose;
    private static List<RelationChoose> relationChooses;

    /**
     * 初始化方法,避免数据残留
     */
    private static void init() {
        editChoose = new HashMap<>();
        relationChooses = new ArrayList<>();
    }

    /**
     * 第一种策略 [0,0],双向关注
     */
    static class FirstStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            // 设置我的可选项
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            relationChooses.add(new RelationChoose("2", "取消关注","http://101.43.99.167:9000/blue-oss/cancle.png"));
            relationChooses.add(new RelationChoose("4", "发私信","http://101.43.99.167:9000/blue-oss/chat.png"));
            editChoose.put("relationChooses", relationChooses);
            // 展示页面选项
            editChoose.put("isLoginCurrentUser", "2");
            editChoose.put("editName", "互相关注");
            return editChoose;
        }
    }

    /**
     * 第二种策略 [0,1],我关注对方,对方把我拉黑
     */
    static class SecondStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            // 设置我的可选项
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            editChoose.put("relationChooses", relationChooses);
            // 展示页面选项
            editChoose.put("isLoginCurrentUser", "401");
            editChoose.put("editName", "对方把你拉黑了");
            return editChoose;
        }
    }

    /**
     * 第三种策略 [0,2],我关注了对方,对方未关注我
     */
    static class ThirdStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            // 设置我的可选项
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            relationChooses.add(new RelationChoose("2", "取消关注","http://101.43.99.167:9000/blue-oss/cancle.png"));
            relationChooses.add(new RelationChoose("4", "发私信","http://101.43.99.167:9000/blue-oss/chat.png"));
            editChoose.put("relationChooses", relationChooses);
            // 展示页面选项
            editChoose.put("isLoginCurrentUser", "2");
            editChoose.put("editName", "取消关注");
            return editChoose;
        }
    }

    /**
     * 第四种策略 [0,3],我关注对方,对方移除拉黑我
     */
    static class FourthStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            // 设置我的可选项
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            relationChooses.add(new RelationChoose("2", "取消关注","http://101.43.99.167:9000/blue-oss/cancle.png"));
            relationChooses.add(new RelationChoose("4", "发私信","http://101.43.99.167:9000/blue-oss/chat.png"));
            editChoose.put("relationChooses", relationChooses);
            // 展示页面选项
            editChoose.put("isLoginCurrentUser", "2");
            editChoose.put("editName", "取消关注");
            return editChoose;
        }
    }

    /**
     * 第五种策略 [1,0],我把对方拉黑了,对方关注了我
     */
    static class FifthStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            // 设置我的可选项
            relationChooses.add(new RelationChoose("3", "移除拉黑","http://101.43.99.167:9000/blue-oss/unlock.png"));
            editChoose.put("relationChooses", relationChooses);
            // 展示页面选项
            editChoose.put("isLoginCurrentUser", "401");
            editChoose.put("editName", "你把对方拉黑了");
            return editChoose;
        }
    }

    /**
     * 第六种策略 [1,1],互相拉黑
     */
    static class SixthStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            relationChooses.add(new RelationChoose("3", "移除拉黑","http://101.43.99.167:9000/blue-oss/unlock.png"));
            editChoose.put("relationChooses", relationChooses);
            // 展示页面选项
            editChoose.put("isLoginCurrentUser", "401");
            editChoose.put("editName", "暂无法查看对方的动态");
            return editChoose;
        }
    }

    /**
     * 第七种策略 [1,2],我拉黑了对方,对方取消关注我
     */
    static class SeventhStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            relationChooses.add(new RelationChoose("3", "移除拉黑","http://101.43.99.167:9000/blue-oss/unlock.png"));
            editChoose.put("relationChooses", relationChooses);
            // 展示页面选项
            editChoose.put("isLoginCurrentUser", "401");
            editChoose.put("editName", "你把对方拉黑了");
            return editChoose;
        }
    }

    /**
     * 第八种策略 [1,3],我拉黑了对方,对方移除拉黑我
     */
    static class EighthStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            relationChooses.add(new RelationChoose("3", "移除拉黑","http://101.43.99.167:9000/blue-oss/unlock.png"));
            editChoose.put("relationChooses", relationChooses);
            // 展示页面选项
            editChoose.put("isLoginCurrentUser", "401");
            editChoose.put("editName", "你把对方拉黑了");
            return editChoose;
        }
    }

    /**
     * 第九种策略 [2,0],我取消关注对方,对方关注我
     */
    static class NinthStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            relationChooses.add(new RelationChoose("0", "回关","http://101.43.99.167:9000/blue-oss/add-person.png"));
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            editChoose.put("relationChooses", relationChooses);
            editChoose.put("isLoginCurrentUser", "0");
            editChoose.put("editName", "回关");
            return editChoose;
        }
    }

    /**
     * 第十种策略 [2,1],我取消关注对方,对方拉黑我
     */
    static class TenthStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            editChoose.put("relationChooses", relationChooses);
            editChoose.put("isLoginCurrentUser", "401");
            editChoose.put("editName", "对方把你拉黑了");
            return editChoose;
        }
    }

    /**
     * 第十一种策略 [2,2],互相取消关注
     */
    static class EleventhStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            relationChooses.add(new RelationChoose("0", "关注","http://101.43.99.167:9000/blue-oss/add-person.png"));
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            editChoose.put("relationChooses", relationChooses);
            editChoose.put("isLoginCurrentUser", "0");
            editChoose.put("editName", "关注");
            return editChoose;
        }
    }

    /**
     * 第十二种策略 [2,3],我取消关注对方,对方移除拉黑我
     */
    static class TwelfthStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            relationChooses.add(new RelationChoose("0", "关注","http://101.43.99.167:9000/blue-oss/add-person.png"));
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            editChoose.put("relationChooses", relationChooses);
            editChoose.put("isLoginCurrentUser", "0");
            editChoose.put("editName", "关注");
            return editChoose;
        }
    }

    /**
     * 第十三种策略 [3,0],我移除拉黑对方,对方关注我
     */
    static class ThirteenthStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            relationChooses.add(new RelationChoose("0", "回关","http://101.43.99.167:9000/blue-oss/add-person.png"));
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            editChoose.put("relationChooses", relationChooses);
            editChoose.put("isLoginCurrentUser", "0");
            editChoose.put("editName", "回关");
            return editChoose;
        }
    }

    /**
     * 第十四种策略 [3,1],我移除拉黑对方,对方拉黑我
     */
    static class FourteenthStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            editChoose.put("relationChooses", relationChooses);
            editChoose.put("isLoginCurrentUser", "401");
            editChoose.put("editName", "对方把你拉黑了");
            return editChoose;
        }
    }

    /**
     * 第十五种策略 [3,2],我移除拉黑对方,对方取消关注我
     */
    static class FifteenthStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            relationChooses.add(new RelationChoose("0", "关注","http://101.43.99.167:9000/blue-oss/add-person.png"));
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            editChoose.put("relationChooses", relationChooses);
            editChoose.put("isLoginCurrentUser", "0");
            editChoose.put("editName", "关注");
            return editChoose;
        }
    }

    /**
     * 第十六种策略 [3,3],互相移除拉黑
     */
    static class SixteenthStrategy implements RelationStrategy {
        @Override
        public Map<String, Object> combineRelationTypes(String relationType1, String relationType2) {
            init();
            relationChooses.add(new RelationChoose("0", "关注","http://101.43.99.167:9000/blue-oss/add-person.png"));
            relationChooses.add(new RelationChoose("1", "设置拉黑","http://101.43.99.167:9000/blue-oss/lock.png"));
            editChoose.put("relationChooses", relationChooses);
            editChoose.put("isLoginCurrentUser", "0");
            editChoose.put("editName", "关注");
            return editChoose;
        }
    }
}

 

 

 

posted @ 2024-08-27 17:12  橘子味芬达水  阅读(50)  评论(0编辑  收藏  举报