2

我需要以某种方式验证 websocket 请求。

有没有办法使用带有reactor-netty的spring webflux来实现?

  • spring-boot 2.0.5.Release
  • 反应堆-netty 0.7.9.Release
4

1 回答 1

2

这些版本包含使用 websocket 定制某些东西的有限可能性。我发现的唯一方法是扩展 HandshakeWebSoketService:

public class CustomHandshakeWebSocketService extends HandshakeWebSocketService {

  public CustomHandshakeWebSocketService(
      RequestUpgradeStrategy upgradeStrategy
  ) {
    super(upgradeStrategy);
  }

  @Override
  public Mono<Void> handleRequest(
      ServerWebExchange exchange,
      WebSocketHandler handler
  ) {
    ServerHttpRequest request = exchange.getRequest();
    if ( //do some validation and if valid delegate to chain) {

      return super.handleRequest(exchange, handler);
    }
    // If not valid, return error
    return Mono
        .error(new ResponseStatusException(HttpStatus.BAD_REQUEST, "Invalid request"));
  }
}

然后我们必须注册该自定义服务:

@Bean
public WebSocketHandlerAdapter handlerAdapter() {
  return new WebSocketHandlerAdapter(webSocketService());
}

@Bean
public WebSocketService webSocketService() {
 ReactorNettyRequestUpgradeStrategy strategy = new ReactorNettyRequestUpgradeStrategy();
    return new CustomHandshakeWebSocketService(strategy);
}
于 2018-09-25T10:17:09.890 回答