Spring Cloud Gateway first experience

Posted by horstuff on Sat, 22 Jan 2022 12:09:28 +0100

brief introduction

Spring Cloud Gateway is the second-generation gateway framework officially launched by Spring Cloud, replacing Zuul gateway. As the of traffic, gateway plays a very important role in microservice system. The common functions of gateway include routing forwarding, permission verification, current limit control and so on. This article first uses official cases to lead you to experience some simple functions of Spring Cloud. In subsequent articles, I will use detailed cases and source code analysis to explain Spring Cloud Gateway in detail

Create project

The source code of this case is downloaded from Official case , you can also download it on my Github. The Spring Boot version used in the project is 2.0.5 Release, the Spring Cloud version is Finchley SR1.

Create a new project named sc-f-gateway-first-sight, and reference the dependencies required by the project in the pom file of the project, including spring boot and spring cloud, and the start of gateway depends on spring cloud starter gateway. The code is as follows:

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

Note: for detailed pom File Dependencies, see the source code.

Create a simple route

In the spring cloud gateway, use the Bean of RouteLocator for routing forwarding, process the request, and finally forward it to the downstream service of the target. In this case, the request is forwarded to http://httpbin.org:80 On this address. The code is as follows:

@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();
    }
    
    }

In the above myRoutes method, a RouteLocatorBuilder bean is used to create routes. In addition to creating routes, RouteLocatorBuilder allows you to add various predictions and filters. Predictions assertion means that specific routes are processed according to specific request rules. Filters are various filters, Used to make various judgments and modifications to requests.

The route created above allows the request "/ get" to be forwarded to“ http://httpbin.org/get ”. On the route configuration, we have added a filter, which will add a header to the request. The key is hello and the value is world.

Start the springboot project on the browser http://localhost:8080/get , the browser displays as follows:

{   "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" 
    }

It can be seen that when we request "/ get" from the gateway project, the gateway will forward the project request to“ http://httpbin.org/get ”And before forwarding, add a filter, which will add a header to the request, with the key as hello and the value as world.

Note that HTTP bin shows the header hello and the value world of the request.

Using Hystrix

You can use hystrix in the spring cloud gateway. Hystrix is a service component of spring cloud and plays a very important role in microservice system. Hystrix is used as a filter in the spring cloud gateway. The code is as follows:

   @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();
    }

In the above code, we use another router, which uses the host to assert whether the request enters the route. When the requested host has "*. hystrix.com", it will enter the router. There is a hystrix filter in the router, which can configure the name, and the logical address of the directional fallback. For example, in this case, it is redirected to "/ fallback".

Now write a logic of "/ fallback":

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

Mono is a Reactive stream that outputs a "fallback" string.

Use curl to execute the following command:

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

The response returned is:

fallback

Visible, with hostwww hystrix. Com's request implements the fallback logic of hystrix.

summary
This article explains the simple usage of spring cloud gateway through a simple official case. There are two important concepts in spring cloud gateway, predictions and filters, which will be explained in subsequent articles. Coming soon.

Source download
https://gitee.com/frey6/spring-cloud-learn

Topics: Java Spring Cloud gateway