【问题标题】:Apache Camel Content Based Routing on Websocket Connections基于 Apache Camel 内容的 Websocket 连接路由
【发布时间】:2016-02-18 15:24:48
【问题描述】:

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

【问题讨论】:

  • 你的意思是camel对包含clientid的json消息执行添加调用吗?
  • 没有。我想让骆驼从消息中拉出clientId。通过 clientId 从收件人列表中查找 websocket。
  • 这应该通过choice() 和when() 来完成。但是应该可以正常工作。

标签: apache-camel java-websocket


【解决方案1】:

是的,这是可能的。您可以通过以下方法检索每个客户端的 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 : 一个唯一的连接键,你可以从 websocket 消费者的交换头中获得。

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

【讨论】:

  • 你能否解释一下,如何以及在哪里存储来自生产者的连接密钥,以向特定客户端发送消息。
  • @PrinceyJames 您可以将连接密钥存储在静态哈希映射中。如果您的连接绑定到进程或用户,您可以使用其 id 作为密钥和连接密钥作为值。当您的客户端关闭连接时,您应该从此映射中删除连接键。
  • 就我而言,每个连接都绑定到一个进程。在启动进程之前,客户端将使用进程 ID 与服务器建立 websocket 连接,服务器将这个唯一的连接密钥与进程 ID 保存在映射中,并使用进程 ID 和连接密钥发送进程状态。
猜你喜欢
  • 1970-01-01
  • 2017-03-28
  • 2017-02-26
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-09-29
  • 1970-01-01
相关资源
最近更新 更多