我有一个假设的场景:让我假装我有一个Apache Camel websocket服务器,我允许很多websocket连接。每个客户端连接都需要与ClientID相关联。 ClientID是通过InitConnection json消息通过新连接获得的,其中ClientID是消息的成员。问题是:为了执行基于内容的路由,是否可以将一个websocket关联一个websocket实例与ClientID?
答案 0 :(得分:3)
from("direct:Consumer1")
.process(new Processor() {
public void process(Exchange exchange) throws Exception {
Map<String, Object> headers=exchange.getIn().getHeaders();
//you can get a unique connection key from the exchange header.
//store this key somewhere, to send messages to particular client.
String uniqueConnectionKey=headers.get("websocket.connectionKey").toString();
//you can get message from the client like below.
String dataFromClient=exchange.getIn().getBody().toString();
}
}).end();
您需要使用您的客户端ID映射此唯一键,以便您可以使用此UUID将消息发送到特定客户端。
CamelContext camelContext=new DefaultCamelContext();
ProducerTemplate template=camelContext.createProducerTemplate();
template.sendBodyAndHeader("direct:Producer1", {message}, "connectionKey", {connectionkey});
direct:Producer1:生产者端点名称。
connectionkey:一个唯一的连接密钥,您可以从websocket consumer中的exchange头获取。
message:给websocket端点的消息。
编辑: 这是生产者路线。
from("direct:Producer1").
//we will use this connectionKey for uniquely identifying each connection from the client.
setHeader(WebsocketConstants.CONNECTION_KEY, header("connectionKey")).
to("websocket://{host}:{port}/camel-websocket?sendToAll=false").end();