SpringCloud之GateWay动态路由及转发

一、路由配置

1.在pom.xml中引入依赖

 <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>

2.application.yml中写入配置

server:
  port: 8080 #端口
spring:
  application:
    name: api-gateway-server #服务名称
  #配置SpringCloudGateway的路由
  cloud:
    gateway:
      routes:
      #配置路由: 路由id,路由到微服务的uri,断言(判断条件)
      - id: product-service   #保持唯一
        #uri: http://127.0.0.1:9001  #目标微服务请求地址
        uri: lb://service-product #lb://根据微服务名称从注册中心拉取服务请求路径
        predicates:
        - Path=/product/**  #路由匹配条件
#配置Eureka
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka/
  instance:
    prefer-ip-address: true #使用ip地址注册

二、重写转发路径

server:
  port: 8080 #端口
spring:
  application:
    name: api-gateway-server #服务名称
  #配置SpringCloudGateway的路由
  cloud:
    gateway:
      routes:
      #配置路由: 路由id,路由到微服务的uri,断言(判断条件)
      - id: product-service   #保持唯一
        #uri: http://127.0.0.1:9001  #目标微服务请求地址
        uri: lb://service-product #lb://根据微服务名称从注册中心拉取服务请求路径
        predicates:
        #- Path=/product/**  #路由匹配条件
        - Path=/product-service/**  #将当前请求转发到 http://127.0.0.1:9001/product/1
        filters: #配置路由过滤器   http://localhost:8080/product-service/product/1 -->http://127.0.0.1:9001/product/1
        - RewritePath=/product-service/(?<segment>.*), /$\{segment}  #路由重写的过滤器,在yml中 $写为$\
#配置Eureka
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka/
  instance:
    prefer-ip-address: true #使用ip地址注册

三、微服务名称转发

server:
  port: 8080 #端口
spring:
  application:
    name: api-gateway-server #服务名称
  #配置SpringCloudGateway的路由
  cloud:
    gateway:
      routes:
      #配置路由: 路由id,路由到微服务的uri,断言(判断条件)
      - id: product-service   #保持唯一
        #uri: http://127.0.0.1:9001  #目标微服务请求地址
        uri: lb://service-product #lb://根据微服务名称从注册中心拉取服务请求路径
        predicates:
        #- Path=/product/**  #路由匹配条件
        - Path=/product-service/**  #将当前请求转发到 http://127.0.0.1:9001/product/1
        filters: #配置路由过滤器   http://localhost:8080/product-service/product/1 -->http://127.0.0.1:9001/product/1
        - RewritePath=/product-service/(?<segment>.*), /$\{segment}  #路由重写的过滤器,在yml中 $写为$\
      #配置自动的根据微服务名称进行路由转发 http://localhost:8080/service-product/product/1
      discovery:
        locator:
          enabled: true  #开启根据微服务名称自动转发
          lower-case-service-id: true #微服务名称以小写形式呈现
#配置Eureka
eureka:
  client:
    service-url:
      defaultZone: http://localhost:9000/eureka/
  instance:
    prefer-ip-address: true #使用ip地址注册

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 [email protected] 举报,一经查实,本站将立刻删除。

相关推荐