Spring WebFlux WebSocket路径变量

时间:2018-02-27 21:25:42

标签: spring websocket reactive spring-webflux

如何使用spring webflux在websocket处理程序中获取路径变量?
我试过这个:

@Bean
public HandlerMapping webSocketMapping() {
    Map<String, WebSocketHandler> map = new HashMap<>();
    map.put("/path/{id}", session -> session.send(Mono.just(session.textMessage("123"))));
    SimpleUrlHandlerMapping mapping = new SimpleUrlHandlerMapping();
    mapping.setUrlMap(map);
    mapping.setOrder(-1);
    return mapping;
}

但是session没有关于url参数的任何信息 有可能吗?

1 个答案:

答案 0 :(得分:1)

它需要一些强制转换,但是有可能。

private URI getConnectionUri(WebSocketSession session) {
    ReactorNettyWebSocketSession nettySession = (ReactorNettyWebSocketSession) session;
    return  nettySession.getHandshakeInfo().getUri();
  }

有了URI后,请使用Spring UriTemplate获取路径变量。

// This can go in a static final 
UriTemplate template = new UriTemplate("/todos/{todoId}");
Map<String, String> parameters = template.match(uri.getPath());
String todoId = parameters.get("todoId");