代码之家  ›  专栏  ›  技术社区  ›  Rizon

基于Websocket连接的Apache Camel内容路由

  •  1
  • Rizon  · 技术社区  · 9 年前

    我有一个假设场景:假设我有一台Apache Camel网络套接字服务器,并且我允许许多网络套接符连接。每个客户端连接都需要与ClientID相关联。ClientID由新连接通过InitConnection json消息获得,其中ClientID是消息的成员。问题是:为了执行基于内容的路由,是否可以让camel将websocket实例与ClientID相关联?

    1 回复  |  直到 9 年前
        1
  •  5
  •   Shemeem    8 年前

    是的,这是可能的。您可以通过以下方法检索每个客户端的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});
    

    direct:Producer1:生产者端点名称。

    connectionkey:一个唯一的连接键,您可以从websocketconsumer中的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();