springcloud學習筆記——gateway網關

基礎配置


網關作爲一個單獨的微服務,其作用是在負載均衡和微服務提供者之間起到保護、限流作用。
其配置的依賴如下:

<dependency>
     <groupId>org.springframework.cloud</groupId>
     <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>

注意,這裏配置不需要配置web依賴,否則會報錯。


在application.yml配置如下:

server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      routes:
        - id: payment_route # 路由的id,沒有規定規則但要求唯一,建議配合服務名
          uri: http://localhost:8001
          predicates:
            - Path=/payment/discovery/** # 斷言,路徑相匹配的進行路由
        - id: payment_route2
          uri: http://localhost:8001
          predicates:
            Path=/payment/lb/** #斷言,路徑相匹配的進行路由

eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/

配置動態路由

篇日誌動態路由好處就是可以方面擴展微服務,同時在網關處配置動態路由可以實現負載均衡。之前的負載均衡都是由Ribbon的@LoadBalance實現。現在由網關實現。僅配置yml文件即可。

server:
  port: 9527

spring:
  application:
    name: cloud-gateway
  cloud:
    gateway:
      discovery:
        locator:
          enabled: true
      routes:
        - id: payment_route # 路由的id,沒有規定規則但要求唯一,建議配合服務名
          uri: lb://CLOUD-PAYMENT-SERVICE
          predicates:
            - Path=/payment/discovery/** # 斷言,路徑相匹配的進行路由
        - id: payment_route2
          uri: lb://CLOUD-PAYMENT-SERVICE
          predicates:
            Path=/payment/lb/** #斷言,路徑相匹配的進行路由

eureka:
  instance:
    hostname: cloud-gateway-service
  client:
    fetch-registry: true
    register-with-eureka: true
    service-url:
      defaultZone: http://eureka7001.com:7001/eureka/

在這裏配置了打開discovery的locator,即動態路由功能。之後在配置具體uri爲微服務名。動態路由即配置完成。

predicates斷言設置

斷言設置鏈接

- After=2017-01-20T17:42:47.789-07:00[America/Denver]
- Before=2017-01-20T17:42:47.789-07:00[America/Denver]
- Cookie=username,zzyy
- Header=X-Request-Id, \d+ #請求頭要有X-Request-Id屬性,並且值爲正數
- Host=**.atguigu.com
- Method=GET
- Query=username, \d+ # 要有參數名username並且值還要是正整數才能路由

filter過濾器

指的是Spring框架中GatewayFilter的實例,使用過濾器,可以在請求被路由前或者之後對請求進行修改.

生命週期

僅分爲兩種,pre和post。意思是在路由之前和路由之後

種類

GatewayFilter 具體配置

GlobalFilter 具體配置

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章