2016-02-18 41 views
1

我有一個假設的場景:讓我們假裝我有一個Apache Camel websocket服務器,並且允許多個websocket連接。每個客戶端連接都需要與一個ClientID關聯。 ClientID是通過一個新的連接通過InitConnection json消息獲得的,其中ClientID是消息的成員。問題是:爲了執行基於內容的路由,是否有可能讓駱駝將一個帶有ClientID的websocket實例關聯起來?基於Apache Camel內容的Websocket連接路由

+0

你的意思是駱駝執行添加調用json消息包含clientid? –

+0

不,我想讓駱駝從客戶信息中提取客戶ID。由clientId從recipientList查找websocket。 – Rizon

+0

這應該用choice()和when()來完成。但是,應該工作得很好。 –

回答

2

是的,這是可能的。您可以通過以下方法來檢索每個客戶的UUID:

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}); 

直接:Producer1:生產者端點名稱。

connectionkey:一個唯一的連接密鑰,您將從websocket消費者的交換頭獲得。

消息:給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(); 
+0

您可以解釋一下,如何以及在哪裏存儲生產者的連接密鑰,以便將消息發送到特定的客戶端。 –

+1

@PrinceyJames您可以將連接密鑰存儲在靜態哈希映射中。如果您的連接綁定到進程或用戶,則可以使用其ID作爲鍵和連接鍵作爲值。當你的客戶端關閉連接時,你應該從這張地圖上刪除連接鍵。 – Shemeem

+0

在我的情況下,每個連接都綁定到一個進程。在開始進程之前,客戶端將使用進程ID與服務器建立websocket連接,服務器將此唯一連接密鑰與進程ID保存在映射中,並使用進程ID和連接密鑰發送進程的狀態。 – Shemeem