SpringCloud config gateway 例子

前提条件

Mono和Flux默认情况下是延迟执行的. 如果仅仅只是定义 MonoFlux 但是没有进行 subscribe 的话,是不会执行的.

跳转流程

  1. ![image.png](https://cdn.nlark.com/yuque/0/2020/png/191132/1605624566886-0bbc8751-4d00-46ca-9f34-adbece26ddeb.png#height=455&id=I9h1q&margin=%5Bobject%20Object%5D&name=image.png&originHeight=595&originWidth=443&originalType=binary&ratio=1&size=26813&status=done&style=none&width=339)

Clients make requests to Spring Cloud Gateway. If the Gateway Handler Mapping determines that a request matches a Route, it is sent to the Gateway Web Handler. This handler runs sends the request through a filter chain that is specific to the request. The reason the filters are divided by the dotted line, is that filters may execute logic before the proxy request is sent or after. All “pre” filter logic is executed, then the proxy request is made. After the proxy request is made, the “post” filter logic is executed.

Mono/Flux执行逻辑之前必须先执行subscribe, 找到 Config Gateway 的subscribe等同于抓住🐍的七寸.

#HttpServerHandle
  1. public void onStateChange(Connection connection, State newState) {
  2. if (newState == HttpServerState.REQUEST_RECEIVED) {
  3. try {
  4. if (log.isDebugEnabled()) {
  5. log.debug(format(connection.channel(), "Handler is being applied: {}"), handler);
  6. }
  7. HttpServerOperations ops = (HttpServerOperations) connection;
  8. //圈起来要考
  9. //handler ==> ReactorHttpHandlerAdapter
  10. Mono.fromDirect(handler.apply(ops, ops))
  11. .subscribe(ops.disposeSubscriber());//考试重点
  12. }
  13. catch (Throwable t) {
  14. log.error(format(connection.channel(), ""), t);
  15. //"FutureReturnValueIgnored" this is deliberate
  16. connection.channel()
  17. .close();
  18. }
  19. }
  20. }

找到这里就可以抓住 handler.apply(ops, ops) 一路奔袭即可得出整个流程.

  • ReactorHttpHandlerAdapter
  • HttpWebHandlerAdapter
  • FilteringWebHandler
  • DefaultGatewayFilterChain

责任链模式的典型运用

链接

What is the difference between GatewayFilter and GlobalFilter?