GateWay动态路由配置

  • Post author:
  • Post category:其他


  • 导包

    	<dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-gateway</artifactId>
            </dependency>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
            </dependency>
        </dependencies>
    
  • 主启动类:

    @SpringBootApplication
    @EnableEurekaClient
    public class Gateway9527 {
        public static void main(String[] args) {
            SpringApplication.run(Gateway9527.class,args);
        }
    }
    
  • 两种方法:配置文件配置,或者配置类配置

    • 方法1:配置文件

      server:
        port: 9527
      spring:
        application:
          name: cloud-gateway
      
        cloud:
          gateway:
            discovery:
      	    locator:
      	      enabled: true  #开启从注册中心动态获取路由功能
            routes:
              - id: payment_routh #路由的ID,没有固定规则但要求唯一,建议配合服务名
                uri: http://localhost:8001   #匹配后提供服务的路由地址
                predicates:
                  - Path=/payment/circuit/**   #断言,路径相匹配的进行路由
                  - After=2021-06-07T16:41:36.583681900+08:00[Asia/Shanghai]  #该时间后生效
      
              - id: payment_routh2
                uri: http://localhost:8001
                predicates:
                  - Path=/ok/**   #断言,路径相匹配的进行路由
      
      
      eureka:
        client:
          service-url:
            defaultZone: http://eureka7001.com:7001/eureka
        instance:
          appname: cloud-gateway-service
      
      
    • 方法2:配置类

      @Configuration
      public class GatewayConfig {
          @Bean
          public RouteLocator getRouteLocator(RouteLocatorBuilder routeLocatorBuilder){
              RouteLocatorBuilder.Builder routes = routeLocatorBuilder.routes();
              // 9527/ok/**请求  为8001的/ok/**请求
              routes.route("payment_route",r -> r.path("/ok/**").uri("http://localhost:8001/"));
      
              return routes.build();
          }
      }
      



常用的predicate

Loaded RoutePredicateFactory [After] 时间之后

Loaded RoutePredicateFactory [Before] 时间之前

Loaded RoutePredicateFactory [Between] 时间之间

Loaded RoutePredicateFactory [Cookie]

Loaded RoutePredicateFactory [Header]

Loaded RoutePredicateFactory [Host]

Loaded RoutePredicateFactory [Method] 请求方式(get post…)

Loaded RoutePredicateFactory [Path]

Loaded RoutePredicateFactory [Query]

Loaded RoutePredicateFactory [ReadBody]

Loaded RoutePredicateFactory [RemoteAddr]

Loaded RoutePredicateFactory [Weight]

Loaded RoutePredicateFactory [CloudFoundryRouteService]



版权声明:本文为weixin_45947759原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。