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>    
相關文章
相關標籤/搜索