发布于 2年前

Spring Webflux监控客户端连接断开的方法

Spring webflux的FluxSink有两个方法:onCancel和onDispose。当客户端的连接断开,这两个方法会被调用。

示例代码:

@RestController
public class Controller {
  @GetMapping("/")
  public Flux<String> test() {
    return Flux.create(this::process);
  }
  private void process(final FluxSink<String> sink) {
    sink.onRequest(i -> {
      for (int j = 0; j < i; j++) {
        sink.next("Hello world" + j);
      }
    });
    sink.onCancel(() -> System.out.println("Flux Canceled"));
    sink.onDispose(() -> System.out.println("Flux dispose"));
  }
}
©2020 edoou.com   京ICP备16001874号-3