ICode9

精准搜索请尝试: 精确搜索
首页 > 其他分享> 文章详细

网关路由配置解析

2021-08-13 16:32:38  阅读:305  来源: 互联网

标签:网关 swagger service platform routes Path 解析 路由


  1. gateway配置
server:
  port: 9001


spring:
  application:
    name: platform-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true
      routes:
        - id: platform-service111
          uri: lb://platform-service
          predicates:
            - Path=/platform-service/**
        - id: platform-redis222
          uri: lb://platform-redis
          predicates:
            - Path=/platform-redis/**

      default-filters:   # 配置跨域,header去重
        - DedupeResponseHeader=Vary Access-Control-Allow-Credentials Access-Control-Allow-Origin, RETAIN_UNIQUE
        - DedupeResponseHeader=Access-Control-Allow-Origin, RETAIN_FIRST
        - AddResponseHeader=Access-Control-Allow-Credentials,true



eureka:
  instance:
    prefer-ip-address: true
    instance-id: ${spring.cloud.client.ip-address}:${server.port}
  client:
    service-url:
      register-with-eureka: true
      fetch-registy: true
      defaultZone: http://172.10.101.123:7001/eureka/


gateway动态路由规则

cloud:
    gateway:
      discovery:
        locator:
          enabled: true
          lower-case-service-id: true

使用这部分配置即可实现微服务名称自动进行动态路由配置,不需要再进行routes配置。

gateway的Path路径匹配规则

	routes:
        - id: platform-service111
          uri: lb://platform-service
          predicates:
            - Path=/user/**

断言规则:platform-service-ip:port/user/** = gateway-ip:port/user/**

重点:整合swagger

  1. 首先需要两个类:SwaggerResourcesConfig和SwaggerResourceController
@Component
@Primary
@AllArgsConstructor
public class SwaggerResourcesConfig implements SwaggerResourcesProvider {
    public static final String API_URI = "/v2/api-docs";
    private final RouteLocator routeLocator;
    private final GatewayProperties gatewayProperties;

    /**
     * 这个类是核心,这个类封装的是SwaggerResource,即在swagger-ui.html页面中顶部的选择框,选择服务的swagger页面内容。
     * RouteLocator:获取spring cloud gateway中注册的路由
     * RouteDefinitionLocator:获取spring cloud gateway路由的详细信息
     * RestTemplate:获取各个配置有swagger的服务的swagger-resources
     */
    @Override
    public List<SwaggerResource> get() {
        List<SwaggerResource> resources = new ArrayList<>();
        List<String> routes = new ArrayList<>();
        //取出gateway的route
        routeLocator.getRoutes().subscribe(route -> routes.add(route.getId()));
        //结合配置的route-路径(Path),和route过滤,只获取有效的route节点
        gatewayProperties.getRoutes().stream().filter(routeDefinition -> routes.contains(routeDefinition.getId()))
                .forEach(routeDefinition -> routeDefinition.getPredicates().stream()
                        .filter(predicateDefinition -> ("Path").equalsIgnoreCase(predicateDefinition.getName()))
                        .forEach(predicateDefinition -> resources.add(swaggerResource(routeDefinition.getId(),
                                predicateDefinition.getArgs().get(NameUtils.GENERATED_NAME_PREFIX + "0")
                                        .replace("/**", API_URI)))));
        return resources;
    }

    private SwaggerResource swaggerResource(String name, String location) {
        SwaggerResource swaggerResource = new SwaggerResource();
        swaggerResource.setName(name);
        swaggerResource.setLocation(location);
        swaggerResource.setSwaggerVersion("3.0.0");
        return swaggerResource;
    }
}
@RestController
@RequestMapping("/swagger-resources")
public class SwaggerResourceController {
    @Autowired
    private SwaggerResourcesConfig swaggerResources;

    @Autowired(required = false)
    private SecurityConfiguration securityConfiguration;

    @Autowired(required = false)
    private UiConfiguration uiConfiguration;

    @Autowired
    public SwaggerResourceController(SwaggerResourcesConfig swaggerResources) {
        this.swaggerResources = swaggerResources;
    }

    @GetMapping("/configuration/security")
    public Mono<ResponseEntity<SecurityConfiguration>> securityConfiguration() {
        return Mono.just(new ResponseEntity<>(
                Optional.ofNullable(securityConfiguration).orElse(SecurityConfigurationBuilder.builder().build()), HttpStatus.OK));
    }

    @GetMapping("/configuration/ui")
    public Mono<ResponseEntity<UiConfiguration>> uiConfiguration() {
        return Mono.just(new ResponseEntity<>(
                Optional.ofNullable(uiConfiguration).orElse(UiConfigurationBuilder.builder().build()), HttpStatus.OK));
    }

    @GetMapping("")
    public Mono<ResponseEntity> swaggerResources() {
        return Mono.just((new ResponseEntity<>(swaggerResources.get(), HttpStatus.OK)));
    }
}
  1. 通过SwaggerResourcesConfig 知道,我们需要再gateway中配置routes
routes:
  - id: platform-service111
    uri: lb://platform-service
    predicates:
      - Path=/platform-service/**
  - id: platform-redis222
    uri: lb://platform-redis
    predicates:
      - Path=/platform-redis/**

参考SwaggerResourcesConfig 中的配置,可以知道id是swagger-ui.html页面中顶部的选择框的内容。

当我们切换选择框中的id时,会自动进行路由匹配。在这里又涉及到一个微服务进行动态路由转发的问题:

  • 网关请求的路径为http://localhost:9001/platform-service/v2/api-docs,但实际上访问的是http://localhost:8001/v2/api-docs,这里是localhost:9001/platform-service/覆盖localhost:8001/
    我猜想这是因为我们在前面通过enabled: true配置了动态路由转发,swagger配置类中结合了Path的路径拼接成了/localhost:9001/platform-service/v2/api-docs。但是这里并没有走uri+predicates的路径,所以没有出现路径错误的问题。(所以这里的route是针对swagger的路由设置的,不是gateway动态路由转发的路由配置)
    在这里插入图片描述
    (上图中显示的BaseURL说明是走的 locator 路由)
  • 还有一种情况是:比如我们不通过网关,直接访问微服务的swagger地址为:localhost:8001/ps/v2/api-docs;然后我们配置文件中这样写:
routes:
  - id: platform-service111
    uri: lb://platform-service
    predicates:
      - Path=/ps/**

在这里插入图片描述
(上图中显示的BaseURL说明是走的 routes 路由)
根据路由规则,localhost:9001/ps/** = localhost:8001/ps/** 此时就是只是9001掩盖了8001。
swagger的配置类帮我们拼接了路径:/ps/v2/api-docs
因为这里路径中不是http://localhost:9001/platform-service/,自然不会进行动态路由转发,所有就只是简单的走uri+predicates匹配规则
但是第一种情况是因为开启了动态路由配置,刚好Path的断言规则恰好是它的微服务名称

究极总结:

  1. 配置routes是为了方便swagger选择,通过id进行切换
  2. 由于配置了 locator 会自动进行微服务名进行路由,所以当断言为- Path=/platform-service/**,swagger配置类会进行路径拼接,拼接成http://localhost:9001/platform-service/**,这个时候呢,它走的就不是routes定义的路由匹配了,它走的是 locator 开启的自动根据微服务名进行路由匹配了。
  3. 当断言为- Path=/ps/**,swagger配置类拼接的成的路径为http://localhost:9001/ps/**,因为此时9001跟的不是微服务名称,不能触发 locator 的自动路由匹配,这个时候呢,它走的就不是 locator了,它走的是routes开启的路由匹配。

参考:Spring Cloud Gateway整合Swagger聚合微服务系统API文档(非Zuul) 这篇文章和我的理解又出入,不能理解- Path=/admin/**,他的微服务下面根本没有admin这个路径,怎么匹配的到呢

标签:网关,swagger,service,platform,routes,Path,解析,路由
来源: https://www.cnblogs.com/yzw625/p/15137941.html

本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享;
2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关;
3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关;
4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除;
5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。

专注分享技术,共同学习,共同进步。侵权联系[81616952@qq.com]

Copyright (C)ICode9.com, All Rights Reserved.

ICode9版权所有