Spring Cloud Gateway初體驗

轉載請標明出處: www.fangzhipeng.com/springcloud… 本文出自方誌朋的博客html

這篇文章講述瞭如何簡單地使用Spring Cloud Gateway,來源於Spring Cloud官方案例,地址https://spring.io/guides/gs/gateway 。java

簡介

Spring Cloud Gateway是Spring Cloud官方推出的第二代網關框架,取代Zuul網關。網關做爲流量的,在微服務系統中有着很是做用,網關常見的功能有路由轉發、權限校驗、限流控制等做用。本文首先用官方的案例帶領你們來體驗下Spring Cloud的一些簡單的功能,在後續文章我會使用詳細的案例和源碼解析來詳細講解Spring Cloud Gateway.node

建立工程

本案例的的源碼下載於官方案例,也能夠在個人Github上下載。工程使用的Spring Boot版本爲2.0.5.RELEASE,Spring Cloud版本爲Finchley.SR1。git

新建一個工程,取名爲sc-f-gateway-first-sight在工程的pom文件引用工程所需的依賴,包括spring boot和spring cloud,以及gateway的起步依賴spring-cloud-starter-gateway,代碼以下:github

<parent>
        <groupId>org.springframework.boot</groupId>
        <artifactId>spring-boot-starter-parent</artifactId>
        <version>2.0.5.RELEASE</version>
    </parent>

    <dependencyManagement>
        <dependencies>
            <dependency>
                <groupId>org.springframework.cloud</groupId>
                <artifactId>spring-cloud-dependencies</artifactId>
                <version>Finchley.SR1</version>
                <type>pom</type>
                <scope>import</scope>
            </dependency>
        </dependencies>
    </dependencyManagement>
 <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
複製代碼

** 注:詳細的pom文件依賴,能夠見源碼。**web

建立一個簡單的路由

在spring cloud gateway中使用RouteLocator的Bean進行路由轉發,將請求進行處理,最後轉發到目標的下游服務。在本案例中,會將請求轉發到http://httpbin.org:80這個地址上。代碼以下:spring

@SpringBootApplication
@RestController
public class Application {

    public static void main(String[] args) {
        SpringApplication.run(Application.class, args);
    }
    @Bean
    public RouteLocator myRoutes(RouteLocatorBuilder builder) {
       return builder.routes()
        .route(p -> p
            .path("/get")
            .filters(f -> f.addRequestHeader("Hello", "World"))
            .uri("http://httpbin.org:80"))
        .build();
    }
    
    }
複製代碼

在上面的myRoutes方法中,使用了一個RouteLocatorBuilder的bean去建立路由,除了建立路由RouteLocatorBuilder可讓你添加各類predicatesfilters,predicates斷言的意思,顧名思義就是根據具體的請求的規則,由具體的route去處理,filters是各類過濾器,用來對請求作各類判斷和修改。json

上面建立的route可讓請求「/get」請求都轉發到「httpbin.org/get」。在route…瀏覽器

啓動springboot項目,在瀏覽器上http://localhost:8080/get,瀏覽器顯示以下:springboot

{
  "args": {}, 
  "headers": {
    "Accept": "text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,image/apng,*/*;q=0.8", 
    "Accept-Encoding": "gzip, deflate, br", 
    "Accept-Language": "zh-CN,zh;q=0.9,en;q=0.8", 
    "Cache-Control": "max-age=0", 
    "Connection": "close", 
    "Cookie": "_ga=GA1.1.412536205.1526967566; JSESSIONID.667921df=node01oc1cdl4mcjdx1mku2ef1l440q1.node0; screenResolution=1920x1200", 
    "Forwarded": "proto=http;host=\"localhost:8080\";for=\"0:0:0:0:0:0:0:1:60036\"", 
    "Hello": "World", 
    "Host": "httpbin.org", 
    "Upgrade-Insecure-Requests": "1", 
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/69.0.3497.100 Safari/537.36", 
    "X-Forwarded-Host": "localhost:8080"
  }, 
  "origin": "0:0:0:0:0:0:0:1, 210.22.21.66", 
  "url": "http://localhost:8080/get"
}

複製代碼

可見當咱們向gateway工程請求「/get」,gateway會將工程的請求轉發到「httpbin.org/get」,而且在轉發之…

注意HTTPBin展現了請求的header hello和值world。

使用Hystrix

在spring cloud gateway中可使用Hystrix。Hystrix是 spring cloud中一個服務熔斷降級的組件,在微服務系統有着十分重要的做用。 Hystrix是 spring cloud gateway中是以filter的形式使用的,代碼以下:

@Bean
    public RouteLocator myRoutes(RouteLocatorBuilder builder) {
        String httpUri = "http://httpbin.org:80";
        return builder.routes()
            .route(p -> p
                .path("/get")
                .filters(f -> f.addRequestHeader("Hello", "World"))
                .uri(httpUri))
            .route(p -> p
                .host("*.hystrix.com")
                .filters(f -> f
                    .hystrix(config -> config
                        .setName("mycmd")
                        .setFallbackUri("forward:/fallback")))
                .uri(httpUri))
            .build();
    }

複製代碼

在上面的代碼中,咱們使用了另一個router,該router使用host去斷言請求是否進入該路由,當請求的host有「*.hystrix.com」,都會進入該router,該router中有一個hystrix的filter,該filter能夠配置名稱、和指向性fallback的邏輯的地址,好比本案例中重定向到了「/fallback」。

如今寫的一個「/fallback」的l邏輯:

@RequestMapping("/fallback")
    public Mono<String> fallback() {
        return Mono.just("fallback");
    }

複製代碼

Mono是一個Reactive stream,對外輸出一個「fallback」字符串。

使用curl執行如下命令:

curl --dump-header - --header 'Host: www.hystrix.com' http://localhost:8080/delay/3

複製代碼

返回的響應爲:

fallback
複製代碼

可見,帶hostwww.hystrix.com的請求執行了hystrix的fallback的邏輯。

總結

本文經過官方的一個簡單的案例,來說解了spring cloud gateway的簡單用法,在spring cloud gateway中有2個重要的概念predicatesfilters,它們個將會在後續文章講解。敬請期待。

源碼下載

github.com/forezp/Spri…


掃碼關注公衆號有驚喜

(轉載本站文章請註明做者和出處 方誌朋的博客

相關文章
相關標籤/搜索