Riz*_*zon 1 apache-camel java-websocket
我有一个假设的场景:让 \xe2\x80\x99s 假装我有一个 Apache Camel Websocket 服务器,并且 I\xe2\x80\x99m 允许许多 Websocket 连接。每个客户端连接都需要与一个 ClientID 关联。ClientID 是由新连接通过 InitConnection json 消息获取的,其中 ClientID 是消息的成员。问题是:camel 是否可以将 websocket 实例与 ClientID 关联起来以执行基于内容的路由?
\n对的,这是可能的。您可以通过以下方法检索每个客户端的 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();
Run Code Online (Sandbox Code Playgroud)
您需要将此唯一密钥与您的客户端 ID 进行映射,以便您可以使用此 UUID 向特定客户端发送消息。
CamelContext camelContext=new DefaultCamelContext();
ProducerTemplate template=camelContext.createProducerTemplate();
template.sendBodyAndHeader("direct:Producer1", {message}, "connectionKey", {connectionkey});
Run Code Online (Sandbox Code Playgroud)
direct:Producer1 :生产者端点名称。
connectionkey :一个唯一的连接密钥,您可以从 websocket Consumer 的交换标头中获取该密钥。
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();
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1415 次 |
| 最近记录: |