我這想到一個點對點聊天的方法,不用沒割人都建立一個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>