content: package jnpf.handler;
  
  import com.alibaba.csp.sentinel.adapter.gateway.sc.callback.GatewayCallbackManager;
  import com.alibaba.csp.sentinel.slots.block.BlockException;
  import jnpf.util.JsonUtil;
  import jnpf.base.ActionResult;
  import org.springframework.core.io.buffer.DataBuffer;
  import org.springframework.http.server.reactive.ServerHttpResponse;
  import org.springframework.web.reactive.function.server.ServerResponse;
  import org.springframework.web.server.ServerWebExchange;
  import org.springframework.web.server.WebExceptionHandler;
  import reactor.core.publisher.Mono;
  
  /**
   * 自定义限流异常处理
   *
   * @author JNPF开发平台组
   * @version V3.1.0
   * @copyright 引迈信息技术有限公司（https://www.jnpfsoft.com）
   * @date 2021-03-24
   */
  public class SentinelHandler implements WebExceptionHandler {
  
      private Mono<Void> writeResponse(ServerResponse response, ServerWebExchange exchange) {
          ServerHttpResponse serverHttpResponse = exchange.getResponse();
          ActionResult result = ActionResult.fail("请求超过最大数");
          DataBuffer buffer = serverHttpResponse.bufferFactory().wrap(JsonUtil.getObjectToString(result).getBytes());
          return serverHttpResponse.writeWith(Mono.just(buffer));
      }
  
      @Override
      public Mono<Void> handle(ServerWebExchange exchange, Throwable ex) {
          if (exchange.getResponse().isCommitted()) {
              return Mono.error(ex);
          }
          if (!BlockException.isBlockException(ex)) {
              return Mono.error(ex);
          }
          return handleBlockedRequest(exchange, ex).flatMap(response -> writeResponse(response, exchange));
      }
  
      private Mono<ServerResponse> handleBlockedRequest(ServerWebExchange exchange, Throwable throwable) {
          return GatewayCallbackManager.getBlockHandler().handleRequest(exchange, throwable);
      }
  }
  