Technology Sharing

gateway

2024-07-12

한어Русский языкEnglishFrançaisIndonesianSanskrit日本語DeutschPortuguêsΕλληνικάespañolItalianoSuomalainenLatina

Gateway Core Concepts

1. Route
Routing is the most basic part of the gateway. Routing information consists of an ID, a destination URI, a set of assertion factories, and a set of filters. If the assertion is true, it means that the requested URL matches the configured route.
2. Predicates
     The assert function allowsDevelopers definematchHTTP requestAny information, such as request headers and parameters, etc.
3. Filter
Filters are divided into Gateway Filters and Global Filters. Filters can process requests and responses.


Gateway Quick Start

1. Introducing dependencies
Note: This will conflict with the dependencies of spring-webmvc, so you need to exclude spring-webmvc
2. Write the yml configuration file
server.port = 8088 is Gateway access port
spring.application.name is The service name of the current gateway service
The routing rules are defined below in gateway.routes:
id is the name of this routing rule. There can be many routing rules under gateway.routes
url: Access the service of the current gateway. Which URL to forward toFirst of all, I can't forward all requests to the gateway. Certain conditions must be met. Predicates play this role.
predicates: when The request reaches the current gateway(So This request must carry the current gateway ip + port number The information is followed by a slash /, so the gateway can assume that this information exists.This information does not need to be considered in predicates), If the URL after the port number starts with /order-serv/**,So Just forward it to the IP + port of the above URL. and slash / All subsequent paths will not be removed, then it is forwarded to the address http://localhost:8020/order-serv/order/add
(order-serv is the service name, to prevent the order service from having an address starting with /order/add, and the inventory service also has an address starting with /order/add, so Requests sent to the gateway are accompanied by the name of the service to be forwarded),but There is no /order-serv/ in the request received by the order service, only the request sent is http://localhost:8020/order/add, can it be received, so Let the gateway remove the first layer path, filter prefixes through filters
If the assertion is not met, a 404 error will be reported


Here we have hard-coded the forwarding URL addresses in the configuration. When the server is migrated, the IP address will change or the server is deployed in a cluster, and nginx is needed for reverse proxy and load balancing, which is very troublesome.

We can easily solve these problems by integrating gateway and nacos

Integrate Nacos

1. Continue to introduce nacos dependencies
2. Continue writing the yml configuration file
(1) To integrate nacos, just register the current gateway service to nacos and write the nacos service address and account password
(2) Change the address of the service to which the routing rule is forwarded to to the service name "order-service" (url: order-service). Because you need to use the load balancing strategy of ribbon that comes with nacos, add lb:// in front, lb means load balancing.
The gateway will replace the entire "order-service" with the IP address of one of the order services (because the gateway will periodically pull the IP address list of various services registered on nacos)
This solves the problem that when the server is migrated, the IP address changes, or the server is deployed in the form of a cluster, nginx is still needed for reverse proxy and load balancing.
Abbreviated routing rules: convention over configuration
(1) After enabling the automatic identification of nacos services, there is no need to write assertion rules.
(2) When the request sent to the gateway starts with the service name registered on nacos, it will be automatically forwarded to a server of that service and the first layer path will be automatically filtered out (disadvantage: routing rules are not flexible enough)
At this time, as long as you access it according to the format of gateway address/microservice/interface, you can get a successful response.


Assertion Factory

Assertions are made based on the URL. This is the built-in assertion factory in the gateway.



Custom route assertion factories

Here we assume that we customize an assertion factory based on the query request parameters, copy the content in the source code, and then modify it as needed

customize A predicate factory based on the Query request parameters, You need to inherit the AbstractRoutePredicateFactory class and rewrite the logic of the apply method. In the apply method, you can get the ServerHttpRequest object through exchange.getRequest(), so as to obtain the request parameters, request method, request header and other information.
1. Must be a spring component, that is, a bean
2. The class must be added RoutePredicateFactory As an ending
3. Must inherit AbstractRoutePredicateFactory
4. You must declare a static inner class and declare properties to receive the corresponding assertion information in the configuration file
5. Need to combine shortcutFieldOrder Binding
6. Use apply to make logical judgments. True means the match is successful and false means the match fails.


Filters (filter before routing)

(1) First, the requested URL address is processed by the filter, or some request headers, cookies, etc. are added, deleted, or modified.

(2) Then route to the corresponding server through the nacos service list

The role of the filter: When a request comes to the gateway, we can perform business logic processing on the request.

for example:

(1) Use the filter to filterRemove the first layer path

(2) You can add a request header to all requests coming to the gateway and then set the content inside.

(3) You can set a cookie for all requests coming to the gateway and process it

For details on all the built-in filters, please visit the official website

https://docs.spring.io/spring-cloud-gateway/docs/current/reference/html/#gatewayfilter-factories

Here are some code examples:

The test address is sent to the gateway

Routes to the following @GetMapping address, and the following code is used to receive requests and respond

example 1:

Example 2
Example 3
The previous URL address is sent to the gateway, and after passing through the filter, the prefix /mall-order is added. At this time, the server must be able to receive the response and must set it so that all incoming requests carry /mall-order. This way, the server can normally receive requests routed by the gateway.
Example 4
All requests sent to the current gateway will be routed to the Baidu website
302 is the response status code after redirection


Custom Filters



Global Filters

The difference between local filters and global filters:
Local: Local for a certain route, needs to be configured in the route
Global: for all routing requests, no need toConfigured in the configuration file, Once defined, it will be used
Built-in global filters:
If the route address contains lb, the load balancing strategy will be automatically adopted, corresponding to the first global filter above
These global filters will automatically determine and process, without our management


Custom global filters (important points)

Record all incoming requests and save them in log format. You can use custom global filters

Or you can also customize global filters to determine user login and permissions

Customizing global filters is very simple
1. Define a class and hand it over to the springIOC container for management, that is, add spring annotations @Compenent
2. Inheriting the GlobalFilter interface, rewrite the filter method inside, just write the method body inside
3. Parameter exchangein Included Enter this gatewayAll information requested, extract the URL address, header, cookies, path parameters and all other information, and then perform the corresponding Business Processing
4. return chain.filter(exchange) Release the request


Request Logging

In the gateway microservice, add this command here to enable logging, and record all requests passing through the gateway, but only output to the console



Gateway cross-domain configuration

Cross-domain: When the http request is not on the same IP + the same port, it is called cross-domain

(Only the same IP + the same port can be called the same domain, and both are met.)

1. Through yml configuration , configured at the next level of gateway

The configuration content can be modified cross-domain
2. Set by configuration class


Sentinel combined with gateway

Combined with Sentinel's request to the gateway, flow control downgrade is performed

Sentinel is divided into two parts
Prerequisite: Download the Sentinel client from the remote server, install and run it
The gateway service only needs to:
The configuration file of the gateway service plus the IP+port, account and password of the sentinel client
This integrates the flow control downgrade of sentinel
Sentinel has special rules for gateway servicesIts interface is different from the flow control degradation interface for the method (service entry) in the controller.
You can limit the flow of these rules in the assertion factory
You can limit the flow of a certain IP, remote domain name, request header, parameters in the URL, and cookie values.


Customize the response content of sentinel combined with gateway

existAfter the gateway layer is downgraded or fused by sentinel flow control, it will respond to the requester with the following content

If this content is not what we want, we need to customize the way to respond to the exception. There are two ways

Method 1: (Simple)

 

In the yml configuration, write the above content in layers.

spring . cloud . sentinel . scg . fallback . response body = '{"code":403,"mes":" Current limit "}'
The content after response-body is our customized response content (json format) , the content written is the content of the response
Method 2:

Set the response status code, response type (json format), response content ("Downgraded!")



Gateway High Availability