Network Security Internet Technology Development Database Servers Mobile Phone Android Software Apple Software Computer Software News IT Information

In addition to Weibo, there is also WeChat

Please pay attention

WeChat public account

Shulou

Analysis on the use of the latest version of SpringCloud Gateway2020.0.2

2025-04-15 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >

Share

Shulou(Shulou.com)06/01 Report--

This article mainly introduces the relevant knowledge of "the latest version of SpringCloud Gateway2020.0.2 usage Analysis". The editor shows you the operation process through the actual case. The operation method is simple, fast and practical. I hope this "SpringCloud Gateway2020.0.2 latest version usage Analysis" article can help you solve the problem.

As a new project in SpringCloud, SpringCloud Gateway aims to replace the Zuul gateway.

Brief introduction

The version used in this article is

SpringCloud version 2020.0.2

Spring-cloud-starter-gateway version 3.0.2

Spring-boot-starter version 2.4.4

This project provides a library for building API gateways on top of Spring WebFlux. Spring Cloud Gateway aims to provide a simple and efficient way to route to API and provide them with cross-domain concerns such as security, monitoring / metrics, and resilience.

Features

Based on Spring Framework 5 and Spring Boot 2. 0

Can match the route on any request attribute.

Predicates and filters are specific to routes.

Circuit breaker integration.

Spring Cloud DiscoveryClient integration

Predicates and filters that are easy to write

Request rate limit

Path rewriting

Concept

What is routing?

Routing is the basic module for building a gateway, which consists of ID, destination URI, a series of assertions and filters. If the assertion is true, the route is matched.

What is an assertion?

Developers can match everything in a HTTP request (such as request headers or request parameters) and route if the request matches the assertion

What is filtering?

It is worth to be an instance of GatewayFilter in the Spring framework. Using filters, requests can be modified before / after being routed.

Then let's first get a general idea of the use of gateway through a few small demo, and then we'll learn more about it, so it's easier to understand.

Standalone code (static routing) depends on coordinates

Pom.xml

Org.springframework.boot spring-boot-starter 2.4.4 org.springframework.cloud spring-cloud-starter-gateway 3.0.2 configuration

Select one of the configuration files and configuration classes for ok

According to this configuration, visiting http:localhost:9527/s will be forwarded directly to the home page of Baidu, and the content of the page will display the content of Baidu home page.

Application.yml

Server: port: 9527spring: application: name: cloud-gateway # the following is the configuration of gateway cloud: gateway: routes:-id: gateway_route_1 uri: https://www.baidu.com/s predicates:-Path=/s/**

GatewayConfig.java org.example.springcloud.config.GatewayConfig

Package org.example.springcloud.config;import org.springframework.cloud.gateway.route.RouteLocator;import org.springframework.cloud.gateway.route.builder.RouteLocatorBuilder;import org.springframework.context.annotation.Bean;import org.springframework.context.annotation.Configuration;/** * @ Auth: guohui.wang * @ Date: 2021-04-07 11:07 * @ desc: * / @ Configurationpublic class GatewayConfig {/ * *

Forward "ip:$ {server.port} + ${route.path}" to "${route.url}"

*

For example, "120.0.0.1pur9527Universe s" is forwarded to "https://www.baidu.com/s"".

*

You can try to visit the following link to get the configuration effect

* "http://localhost:9527/s" *" http://localhost:9527/s?wd=spring" *

* * routes (). Route (parameter 1, parameter 2). Route (parameter 1, parameter 2). * Parameter 1:id. You can get a name at will. Identify this routing rule * Parameter 2: specific routing rule content * * routing rule: * path: the content after the gateway service address (such as "/ s" above) * uri: the location to be forwarded to after meeting the path * @ param builder * @ return * / @ Bean public RouteLocator routes (RouteLocatorBuilder builder) {return builder. Route () .route ("gateway_route_1" R-> r.path ("/ s") .uri ("https://www.baidu.com/s")) .build () }}

Startup class

Org.example.springcloud.GatewayMain9527

Package org.example.springcloud;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@SpringBootApplication@EnableEurekaClientpublic class GatewayMain9527 {public static void main (String [] args) {SpringApplication.run (GatewayMain9527.class, args);} integrated with erueka (dynamic routing)

Dynamic routing is implemented through the micro-service name, so that the corresponding services registered by the service center can be invoked back and forth.

Three micro-services are required, and the service structure:

Parent project

Eureka service, as a registry

Gateway service, as a gateway

Provider service, which is forwarded as a gateway

Parent project

To create a project, select maven (you can also choose SpringInitializr if you like)-> enter the name and related information (my name here is springcloudgateway)-> Click finish to create the project.

Modify pom,pom to add version control

Org.springframework.boot spring-boot-dependencies 2.4.4 pom import org.springframework.cloud spring-cloud-dependencies 2020.0.2 pom import eureka module

To create a project, select maven (you can also choose SpringInitializr if you like)-> enter relevant information-> Finish

The name of the module I use here: cloud-eureka

Add coordinate dependency in pom

Org.springframework.cloud spring-cloud-starter-netflix-eureka-server

Create class EurekaApplication org.example.springcloud.eureka.EurekaApplication

Package org.example.springcloud.eureka;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;@SpringBootApplication@EnableEurekaServerpublic class EurekaApplication {public static void main (String [] args) {SpringApplication.run (EurekaApplication.class, args);}}

Create an application.yml under main/resources and add a configuration

Server: port: 9001eureka: instance: hostname: localhost client: # if you do not register yourself with the registry register-with-eureka: false # means that your client is the registry No need for retrieval service fetch-registry: false service-url: # setting up interaction with eureka server address query service and registration service rely on this address defaultZone: http://${eureka.instance.hostname}:${server.port}/eureka/ verification

There is no problem with starting the service (the console is brief), and visiting http://localhost:9001/ can open the page.

Provider module

This module pretends to be a micro-service that provides services to test whether the gateway works.

To create a project, select maven (you can also choose SpringInitializr if you like)-> enter relevant information-> Finish

The name of the module I use here: cloud-provider

Add coordinate dependency in pom

Org.springframework.boot spring-boot-starter-web org.springframework.cloud spring-cloud-starter-netflix-eureka-client

Create class ProviderApplication org.example.springcloud.provider.ProviderApplication

Package org.example.springcloud.provider;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@SpringBootApplication@EnableEurekaClientpublic class ProviderApplication {public static void main (String [] args) {SpringApplication.run (ProviderApplication.class, args);}}

Create the controller layer class TestController org.example.springcloud.provider.controller.TestController

Package org.example.springcloud.provider.controller;import org.springframework.web.bind.annotation.GetMapping;import org.springframework.web.bind.annotation.RequestMapping;import org.springframework.web.bind.annotation.RestController;@RequestMapping ("/ test") @ RestControllerpublic class TestController {@ GetMapping ("/ lb") public String lb () {return "access successful";}}

Create an application.yml under main/resources and add a configuration

Server: port: 9003spring: application: name: cloud-provider#eureka related configuration eureka: instance: instance-id: cloud-provider-01 client: service-url: defaultZone: http://127.0.0.1:9001/eureka register-with-eureka: true fetch-registry: true Verification

There is no problem with starting the service, and you can get the returned content by visiting http://localhost:9003/test/lb, which means the API is fine.

And open the eureka page http://localhost:9001/ to see that the service has been registered, indicating that the service registration is not a problem.

Gateway module to create a project, select maven (you can also choose SpringInitializr for your preferences)-> enter relevant information-> Finish

The name of the module I use here: cloud-gateway

Add coordinate dependency in pom

Org.springframework.cloud spring-cloud-starter-gateway org.springframework.cloud spring-cloud-starter-netflix-eureka-client

Create class GatewayApplication org.example.springcloud.gateway.GatewayApplication

Package org.example.springcloud.gateway;import org.springframework.boot.SpringApplication;import org.springframework.boot.autoconfigure.SpringBootApplication;import org.springframework.cloud.netflix.eureka.EnableEurekaClient;@SpringBootApplication@EnableEurekaClientpublic class GatewayApplication {public static void main (String [] args) {SpringApplication.run (GatewayApplication.class, args);}}

Create an application.yml under main/resources and add a configuration

Server: port: 9002spring: application: name: cloud-gateway cloud: gateway: discovery: locator: # enable dynamic route creation from registry Use the microservice name to route enabled: true routes:-id: payment_routh3 # lb:// + ${value of the spring.application.name of the target service} path mapped by uri: lb://cloud-provider # to access the path that meets the path value Forward to the corresponding service of the response uri Path predicates:-Path=/test/lb/**#eureka related configuration eureka: instance: instance-id: cloud-gateway-01 client: service-url: defaultZone: http://127.0.0.1:9001/eureka register-with-eureka: true fetch-registry: true verification

And open the eureka page http://localhost:9001/ to see that the service has been registered, indicating that there is no problem with service registration.

Access the http://localhost:9002/test/lb according to the configuration. If the normal return page appears, the gateway configuration is successful.

However, the access should fail at this time, and the following page will appear, accompanied by the following error in the console:

Look, the wrong content is found in our host name. "WRGHO-VIEZQZWFI'" in java.net.UnknownHostException: failed to resolve 'WRGHO-VIEZQZWFI' after 4 queries is my host name.

Don't worry, it's time to add such a configuration to the target service (that is, the provider service) and ok:

This configuration item indicates that when guessing the hostname, the server's IP address should be preferred over the hostname reported by OS

Then restart the provider service and revisit it. If an error of 503 is reported during the visit, please see the gateway console content prompt.

No servers available for service: cloud-provider, which means that although the service has been restarted, it has not yet been registered in the service center. We will wait a little while to register and then try to ok.

Error page and console prompt:

At this point, we should have a general understanding and impression of the use of gateway, and then let's continue to learn relevant knowledge.

Assertion (Predicate)

The developer can match everything in the HTTP request (such as request headers or request parameters) and route if the request matches the assertion.

That is the condition for us to carry out the route jump.

Https://docs.spring.io/spring-cloud-gateway/docs/3.0.2/reference/html/#gateway-request-predicates-factories

But in fact, we still have many kinds of assertions, which we can query through the official documents, and you can see my link below, but you'd better go to the official website to find your own response version of the document to see (God knows whether the future version will make new assertions). And official documents have examples and explanations of responses.

When our gateway service starts, the console business prints out the way we assert.

Spring Cloud Gateway uses route matching as part of the Spring WebFlux HandlerMapping infrastructure. Spring Cloud Gateway includes many built-in routing assertion factories. All of these predicates match the different properties of the HTTP request. You can use multiple route assertion factories with logic and statements.

Type of assertion:

After

This assertion matches requests that occur after the specified date and time.

-After=2017-01-20T17:42:47.789-07:00 [America/Denver]

Before

This assertion matches requests that occur before the specified date and time.

-Before=2017-01-20T17:42:47.789-07:00 [America/Denver]

Between this assertion matches a request that occurs between two specified dates and times.

-Between=2017-01-20T17:42:47.789-07:00 [America/Denver], 2017-01-21T17:42:47.789-07:00 [America/Denver]

Cookie

The assertion takes two parameters, the cookie name and a regexp (this is the Java regular expression). This assertion matches the cookie with the given name and whose value matches the regular expression.

-Cookie=chocolate, ch.p

Header

The assertion takes two parameters, the header name and a regexp (this is the Java regular expression). This assertion matches the header with the given name, and the value of the header matches the regular expression.

-Header=X-Request-Id, d +

Host

The assertion takes one parameter: a list of hostname patterns. This pattern is an Ant-style pattern with. As a delimiter.

This assertion matches the Host header that matches the pattern.

-Host=**.somehost.org,**.anotherhost.org

Method

The assertion takes a method parameter, which is one or more parameters: the HTTP method to match.

-Method=GET,POST

Path

This assertion takes two parameters: a list of Spring PathMatcher schemas and an optional flag called matchTrailingSlash (default is true).

-Path=/red/ {segment}, / blue/ {segment}

Query

This assertion takes two parameters: the required parameter and the optional regexp (this is the Java regular expression). If the request contains query parameters that match the configuration, the route matches.

-Query=green

RemoteAddr

This assertion takes the sources list (minimum size 1), and these sources are CIDR tag (IPv4 or IPv6) strings, such as 192.168.0.1 + 16 (where 192.168.0.1 is the IP address and 16 is the subnet mask).

-RemoteAddr=192.168.1.1/24

ReadBody

This is not written in the documentation, but the console shows that the implementation class ReadBodyRoutePredicateFactory of RoutePredicateFactory writes a little comment when it starts. Assertions can read the principal and run on the principal using user-supplied assertions.

The body is cached in memory, so subsequent calls to assertions do not need to be deserialized again.

Weight

This is not written in the document, but the console shows that the implementation class WeightRoutePredicateFactory of RoutePredicateFactory does not write any comments when it is started.

Filter (Filter)

GatewayFilter allows you to modify incoming HTTP requests or outgoing HTTP responses in some way. The scope of a route filter is a specific route. Spring Cloud Gateway includes many built-in GatewayFilter factories.

The GlobalFilter interface has the same signature as GatewayFilter. These are special filters that are conditionally applied to all routes.

In this document I read, there are two kinds of Filter (GatewayFilter and GlobalFilter)

The GatewayFilter website gives you 31 filter factories (factories generate objects, that is, 31 filters).

The GlobalFilter website gives these 10 filter factories (the factory produces objects, that is, the equivalent of 31 filters)

How do I use it?

Just like Predicate, just add it under spring.cloud.gateway.routes, at the same level as id and uri.

Custom filter

We need to implement the two interfaces GlobalFilter,Ordered for our custom filter.

Implements GlobalFilter,Ordered

What can I do?

Global logging

Unified gateway authentication

……

Our custom filter code

MyLogGatewayFilter.java org.example.springcloud.gateway.filter.MyLogGatewayFilter

Package org.example.springcloud.gateway.filter;import org.springframework.cloud.gateway.filter.GatewayFilterChain;import org.springframework.cloud.gateway.filter.GlobalFilter;import org.springframework.core.Ordered;import org.springframework.http.server.reactive.ServerHttpRequest;import org.springframework.http.server.reactive.ServerHttpResponse;import org.springframework.stereotype.Component;import org.springframework.web.server.ServerWebExchange;import reactor.core.publisher.Mono @ Componentpublic class MyLogGatewayFilter implements GlobalFilter, Ordered {@ Override public Mono filter (ServerWebExchange exchange, GatewayFilterChain chain) {/ / do not need log.info, to save trouble, don't take System.out.println seriously ("entered our custom log filter") / / you can get request, response and so on. It's up to you to do whatever you want. Get it in the next two lines. / / whether you want to judge the parameters, ah, or judge token, or whatever, you can define it yourself. / / ServerHttpRequest request = exchange.getRequest (); / / ServerHttpResponse response = exchange.getResponse (); / / returns chain.filter (exchange); indicates that the filter is passed and the request is passed / / passed to the following filter for processing / / if it is return null;, it is filtered out and failed. Return chain.filter (exchange);} @ Override public int getOrder () {/ / the order in which the filter is loaded, the lower the value, the higher the priority. / / Integer.MIN_VALUE to Integer.MAX_VALUE return 0;}}

Once you have written the custom filter, you can ok it. You don't need to configure it. Just add @ Component to the container.

For example, before we visit the http://localhost:9002/test/lb, the console will print what we printed in the filter, indicating that we have entered the filter.

This is the end of the introduction to the analysis of the use of the latest version of SpringCloud Gateway2020.0.2. Thank you for reading. If you want to know more about the industry, you can follow the industry information channel. The editor will update different knowledge points for you every day.

Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.

Views: 0

*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.

Share To

Development

Wechat

© 2024 shulou.com SLNews company. All rights reserved.

12
Report