Spring Cloud Gateway 路由轉發

簡介

Spring Cloud Gateway是Spring Cloud官方推出的第二代網關框架,取代Zuul網關。網關做爲流量的,在微服務系統中有着很是做用。
網關常見的功能有前端

  • 協議轉換,路由轉發
  • 流量聚合,對流量進行監控,日誌輸出
  • 能夠在網關層作權限的判斷
  • 限流,做爲整個系統的前端工程,對流量進行控制
  • 做爲系統的前端邊界,外部流量只能經過網關才能訪問系統
  • 緩存

如上圖所示,客戶端向Spring Cloud Gateway發出請求。 若是Gateway Handler Mapping肯定請求與路由匹配(這個時候就用到predicate),則將其發送到Gateway web handler處理。 Gateway web handler處理請求時會通過一系列的過濾器鏈。 過濾器鏈被虛線劃分的緣由是過濾器鏈能夠在發送代理請求以前或以後執行過濾邏輯。 先執行全部「pre」過濾器邏輯,而後進行代理請求。 在發出代理請求以後,收到代理服務的響應以後執行「post」過濾器邏輯。這跟zuul的處理過程很相似。在執行全部「pre」過濾器邏輯時,每每進行了鑑權、限流、日誌輸出等功能,以及請求頭的更改、協議的轉換;轉發以後收到響應以後,會執行全部「post」過濾器的邏輯,在這裏能夠響應數據進行了修改,好比響應頭、協議的轉換等。 mysql

增新一個項目 分別是服務提供方provider,消費方comsumer,註冊中心eureka,網關gatewaygit

provider

@RequestMapping("/hello")
@RestController
public class HelloController {
    @GetMapping("")
    public String hello(@RequestParam String name) {
        return "Hello, " + name + "!";
    }
}
複製代碼

comsumer

使用Feign調用github

@CommonsLog
@RequestMapping("/hello")
@RestController
public class HelloController {

    @Autowired
    HelloFeignService helloRemote;

    @GetMapping("/{name}")
    public String index(@PathVariable("name") String name)  {
        log.info("the name is " + name);
        return helloRemote.hello(name) + "\n" + new Date().toString();
    }
    
}
複製代碼

增長 Hystrix 斷路器web

@FeignClient(name = "producer", fallback = HelloFeignProviderHystrix.class)
public interface HelloFeignService {

    /**
     * @param name
     * @return
     */
    @GetMapping("/hello/")
    String hello(@RequestParam(value = "name") String name);

}
複製代碼

gateway

Spring Cloud gateway內置了不少校驗條件謂語(predicate)來實現路由功能。
有兩種方式配置,一種是配置文件application的方式,一種是代碼配置面試

a.application配置:

spring:
  application:
    name: sc-gateway-server
  cloud:
    gateway:
      discovery:
        locator:
          # 是否能夠經過其餘服務的serviceId來轉發到具體的服務實例。默認爲false
          # 爲true,自動建立路由,路由訪問方式:http://Gateway_HOST:Gateway_PORT/大寫的serviceId/**,其中微服務應用名默認大寫訪問
          enabled: true
      routes:
        - id: host_route
          uri: http://httpbin.org:80/get
          predicates:
            - Host=**.csdn.** # 請求域名攜帶csdn的,則轉發
        - id: query_route
          uri: http://httpbin.org:80/get
          predicates:
            - Query=username, zzz* # 請求參數含有username,且值知足zzz開頭的,則轉發(對值的匹配能夠省略)
        - id: header_route
          uri: http://httpbin.org:80/get
          predicates:
            - Header=request, \d+ # 若是請求頭含有request,且爲數字,則轉發

複製代碼

b.代碼配置

gateway也提供了代碼的方式配置,好比咱們註釋掉上面的application配置,而後建一個配置類spring

@Configuration
public class GateWayConfig {

  @Bean
  public RouteLocator routeLocator(RouteLocatorBuilder builder) {
    return builder.routes()
            .route(r -> r.path("/fluent/**")
                    .uri("http://httpbin.org:80/get"))
            .build();

  }

}
複製代碼

在上面的代碼中,咱們使用了一個router,該router使用host去斷言請求是否進入該路由,當請求的host有「/fluent/**」,都會進入該router,重定向到了「httpbin.org:80/get」。sql

Spring Cloud Gateway內置了許多Predict,這些Predict的源碼在org.springframework.cloud.gateway.handler.predicate包中。緩存

列舉各類Predicate以下圖: bash

啓動項目

輸入URL 能夠看到轉到了 comsumer 的地址返回了provider的內容

項目地址:github.com/codeyuyu/Sp…

推薦閱讀

互聯網公司面試必問的Redis題目

互聯網公司面試必問的mysql題目(下)

學習Java進階技術乾貨、實踐分享,職位內推,一塊兒聊聊理想。志同道合的朋友,歡迎你的加入。

相關文章
相關標籤/搜索