Activemq mqtt 点对点聊天实现(转载)

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

1、  建立一个topic,所有人都用匹配订阅的方式订阅以该topic为头的topic,例如:所有人都订阅PTP/#。

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

自定义策略代码:

复制代码
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.xml

 
  
              <policyEntry topic="PTP.>">
        <dispatchPolicy>
                    <clientIdFilterDispatchPolicy/>
                  </dispatchPolicy>
        </policyEntry>    

转载:http://www.cnblogs.com/momofeng/p/5482775.html#undefined

转载于:https://www.cnblogs.com/candyzhmm/p/6092542.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值