Spring中的WebSocketConfigurer addHandler中的路径参数

and*_*nux 3 spring spring-mvc websocket

  • 我使用"TextWebSocketHandler"作为websockets,使用"WebSocketConfigurer"来配置websocket.
  • 我有一个场景,需要处理不同的处理程序实例.

例如:如果我正在为某些项目进行拍卖,那么我需要为每个auctionId生成单独的WebSocketHandler实例.我们可以将"auctionId"作为路径参数附加到网址,以便为不同的竞价生成不同的实例吗?

或者还有其他方法可以实现这一目标吗?

这是我添加处理程序的方式:

@Override
public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
    registry.addHandler(websocketTestHandler(), "/websocket-test");
}
Run Code Online (Sandbox Code Playgroud)

Ser*_*mar 9

如果您想使用a TextWebSocketHandler,您可以将拍卖ID作为URL路径的一部分传递.您必须在握手期间将路径复制到WebSocket会话(这是您可以访问ServerHttpRequest握手是http请求的唯一位置),然后从处理程序中检索属性.

这是实施:

@Configuration
@EnableWebSocket
public class WebSocketConfig implements WebSocketConfigurer {

    @Override
    public void registerWebSocketHandlers(WebSocketHandlerRegistry registry) {
        registry.addHandler(auctionHandler(), "/auction/*")
                .addInterceptors(auctionInterceptor());
    }

    @Bean
    public HandshakeInterceptor auctionInterceptor() {
        return new HandshakeInterceptor() {
            public boolean beforeHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                  WebSocketHandler wsHandler, Map<String, Object> attributes) throws Exception {

                // Get the URI segment corresponding to the auction id during handshake
                String path = request.getURI().getPath();
                String auctionId = path.substring(path.lastIndexOf('/') + 1);

                // This will be added to the websocket session
                attributes.put("auctionId", auctionId);
                return true;
            }

            public void afterHandshake(ServerHttpRequest request, ServerHttpResponse response, 
                    WebSocketHandler wsHandler, Exception exception) {
                // Nothing to do after handshake
            }
        };
    }

    @Bean
    public WebSocketHandler auctionHandler() {
        return new TextWebSocketHandler() {
            public void handleTextMessage(WebSocketSession session, TextMessage message) throws IOException {
                // Retrieve the auction id from the websocket session (copied during the handshake)
                String auctionId = (String) session.getAttributes().get("auctionId");

                // Your business logic...
            }
        };
    }
 }
Run Code Online (Sandbox Code Playgroud)

客户:

new WebSocket('ws://localhost:8080/auction/1');
Run Code Online (Sandbox Code Playgroud)

即使这是一个可行的解决方案,我建议您通过WebSockets查看STOMP,它将为您提供更大的灵活性.