Activemq mqtt 点对点聊天实现

我这想到一个点对点聊天的方法,不用没割人都创建一个topic了,思路仍是自定义一个分发策略,具体以下:node

一、  创建一个topic,全部人都用匹配订阅的方式订阅以该topic为头的topic,例如:全部人都订阅PTP/#。lua

二、  例如A向B发送聊天信息,B的clientId是bbb,A只须要向PTP/bbb 推送聊天信息,我写的自定义策略会针对全部PTP开头的topic作自定义分发<policyEntry topic="PTP.>">,将topic里的clientId解析出来,并将该消息只发给B。spa

自定义策略代码:code

public class ClientIdFilterDispatchPolicy extends SimpleDispatchPolicy {
    public boolean dispatch(MessageReference node,
            MessageEvaluationContext msgContext, List<Subscription> consumers)
            throws Exception {
        System.out.println("--------------------------------来了------------------------------------------");
        System.out.println(node.getMessage().getDestination().getQualifiedName());
        System.out.println(node.getMessage().getDestination().getPhysicalName());
        String topic = node.getMessage().getDestination().getPhysicalName();
        String clientId = topic.substring(topic.indexOf(".")+1, topic.length());
        System.out.println("clientId:" + clientId);
        System.out.println("--------------------------------end------------------------------------------");
        
        if (clientId == null)
            super.dispatch(node, msgContext, consumers);

        ActiveMQDestination destination = node.getMessage().getDestination();

        int count = 0;
        for (Subscription sub : consumers) {
            if (sub.getConsumerInfo().isBrowser()) {
                continue;
            }
            if (!sub.matches(node, msgContext)) {
                sub.unmatched(node);
                continue;
            }
            System.out.println("isTopic:" + destination.isTopic());
            System.out.println("getClientId:" + sub.getContext().getClientId());
            if ((clientId != null)
                    && (destination.isTopic())
                    && (clientId.equals(sub.getContext().getClientId()))
                    ) {
                sub.add(node);
                count++;
            } else {
                sub.unmatched(node);
            }
        }

        return count > 0;
    }

    
}

activemq.xmlxml

              <policyEntry topic="PTP.>">
        <dispatchPolicy>
                    <clientIdFilterDispatchPolicy/>
                  </dispatchPolicy>
        </policyEntry>    
相关文章
相关标签/搜索