What is a gateway
In microservices architecture, the granularity of services is further subdivided, and individual business services can be independently designed, developed, tested, deployed, and managed. At this time, each independent deployment unit can be maintained by different development and test teams, and can be designed using different programming languages and technology platforms, which requires that a language and platform-independent service protocol be used as the communication mode between each unit.
In other words, the gateway provides a unified gateway for all requests, facilitating unified management of service requests and responses.
Why a gateway
An API gateway is a system that sits in front of an application or service that provides REST API interface services to manage authorization, access control, and traffic restrictions, etc., so that REST API interface services are protected by the API gateway and transparent to all callers.
What is a gateway
Spring Cloud Gateway is an official Spring Cloud Gateway developed based on Spring 5.0, Spring Boot 2.0 and Project Reactor technologies. Spring Cloud Gateway aims to provide a simple and effective unified API route management approach for microservices architectures. As a Gateway in the Spring Cloud ecosystem, Spring Cloud Gateway aims to replace ZUUL. It not only provides a unified routing mode, but also provides basic Gateway functions based on Filter chain, such as security, monitoring/burying point, and flow limiting.
How gateway works
The client makes a request to the Spring Cloud gateway. If the gateway handler map determines that the request matches the route, it is sent to the gateway Web handler. The handler runs to send requests through a chain of request-specific filters. The reason the filters are separated by dashed lines is that the filter can perform logic before or after sending the broker request. Perform all the “pre-filter” logic, then issue the proxy request. After the broker request is issued, the “after” filter logic is executed.
Routing rules
Routing and filters are two very important concepts in Gateway, which itself provides a very rich set of routing rules and a variety of filters to suit our needs. The Gateway provides 11 routing rules:
-
Post route predicate factory
This predicate matches requests that occur after the current date and time. The parameter is called After
-
Pre-routing predicate factory
This predicate matches requests that occurred before the current date and time. The parameter is called Before
-
Time segment routing predicate factory
This predicate matches requests that occur after datetime1 and before datetime2. The parameter is called Between
-
Cookie routing predicate factory
This predicate matches the cookie with the given name and the value matches the regular expression. The parameter is called Cookie
-
Header routing predicate factory
The predicate matches the header with the given name and the value matches the regular expression. The parameter is called Header
-
Host route predicate factory
The predicate is matched by routes. When multiple routes are matched, separated by,. The parameter name is Host
-
Method routing predicate factory
This parameter is one or more HTTP methods to match. The parameter name is Method
-
Path-routing predicate factory
This predicate means that a prefix is added to the request path to match. Parameter name is Path
-
Query the routing predicate factory
-
RemoteAddr Route predicate factory
-
Weight route predicate factory
Among them, we commonly use the path routing predicate factory, which, together with StripPrefix GatewayFilter factory, realizes our route matching and forwarding.
The path routing predicate factory configuration is as follows:
Spring: Cloud: gateway: Discovery: locator: enabled: true Spring: Cloud: gateway: Discovery: locator: enabled: true Uri: lb://demo-provider predicates: # Predicates: Path=/demo/**Copy the code
If the request path is /demo/**, the request is forwarded to the Demo-provider service.
Gateway filter
In the Spring Cloud Gateway 2.2.2.RELEASE, 30 filters are implemented by default.
The serial number | Filter plant | role | parameter |
---|---|---|---|
1 | AddRequestHeader | Add the Header for the original request | Header name and value |
2 | AddRequestParameter | Add request parameters to the original request | Parameter name and value |
3 | AddResponseHeader | Add the Header for the original response | Header name and value |
4 | DedupeResponseHeader | Removes duplicate values from the response header | The name of the Header to be deleted and the deduplication policy |
5 | Hystrix | Introduce Hystrix circuit breaker protection for routes | The name of the HystrixCommand |
6 | CircuitBreaker | Introduce Resilience4J circuit breaker protection for routes | The name of the CircuitBreaker |
7 | FallbackHeaders | Add specific exception information to the request header of the fallbackUri | The name of the Header |
MapRequestHeader | Update the Header in the original request | The value of the Header | |
9 | PrefixPath | Prefixes the original request header | The prefix path |
10 | PreserveHostHeader | Add the preserverHostHeader=true attribute to the request, which the routing filter checks to determine whether to send the original host | There is no |
11 | RequestRateLimiter | It is used to limit the traffic of requests. The traffic limiting algorithm is token bucket | KeyResolver, rateLimiter, statusCode, denyEmptyKey, emptyKeyStatus |
12 | RedirectTo | Redirects the original request to the specified URL | HTTP status code and redirected URL |
13 | RemoveHopByHopHeadersFilter | Removes a set of headers specified by the IETF organization for the original request | This is enabled by default, and you can specify which headers to delete only |
14 | RemoveRequestHeader | Delete a Header for the original request | The Header name |
15 | RemoveResponseHeader | Remove a Header for the original response | The Header name |
16 | RewritePath | Override the original request path | The original path regular expression and the rewritten path regular expression |
RewriteLocationResponseHeader | Overrides the response headerLocation The value of the |
||
18 | RewriteResponseHeader | Overrides a Header in the original response | The Header name, the regular expression for the value, and the overridden value |
19 | SaveSession | Enforce the request before forwarding itWebSession::save operation |
There is no |
20 | SecureHeaders | Add a series of response headers for security purposes to the original response | None. You can modify the values of the security response headers |
21 | SetPath | Modifies the original request path | Modified value |
22 | SetRequestHeader | Modifies the value of a Header in the original request | Header name, modified value |
23 | SetResponseHeader | Modify the value of a Header in the original response | Header name, modified value |
24 | SetStatus | Modifies the status code of the original response | The HTTP status code can be a number or a string |
25 | StripPrefix | The path used to truncate the original request | Use numbers to indicate the number of paths to truncate |
26 | Retry | Retry for different responses | Retries, Statuses, Methods, series |
27 | RequestSize | Sets the maximum size of a request packet that can be received. Returns if the request package size exceeds the set value413 Payload Too Large Sets the maximum size of a request packet that can be received. Returns if the request package size exceeds the set value413 Payload Too Large |
Request packet size, in bytes. The default value is 5M |
28 | ModifyRequestBody | Modify the original request body content before forwarding the request | Modified request body content |
29 | ModifyResponseBody | Modify the contents of the original response body | Modified response body content |
30 | Default | Add filters for all routes | Filter factory name and value |
The more commonly used one, such as type 25, is configured as follows:
Spring: Cloud: gateway: Discovery: locator: enabled: true Spring: Cloud: gateway: Discovery: locator: enabled: true -path =/demo/** filters: -stripprefix =1. //demo-provider predicatesCopy the code
If the demo-Provider service has a /test interface, the request path through the gateway should be /demo/test, so that the route can be distributed to the Demo-Provider service. However, the route distributed past is /demo/test, which is different from our actual /test interface. In this case, we use StripPrefix=1 to intercept the level 1 route, so that the forwarded route is /test.
User-defined gateway filters
In addition to the 30 filters provided above, we can also implement custom filters.
1. Implement the GatewayFilter interface and Ordered interface
The gatewayFilter interface is used to filter requests, while the ordered interface is used to set the priority of the filter. A larger value indicates a lower priority.
To implement a custom filter, there are two steps: 1. Implement the filter, 2. Add a filter to a specific route.
public class TokenGatewayFilter implements GatewayFilter.Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
System.out.println("This is where you deal with your own logic.");
return chain.filter(exchange);
}
@Override
public int getOrder(a) {
return 0; }}@Configuration
class RouteConfiguration{
@Bean
public RouteLocator routeLocator(RouteLocatorBuilder builder){
return builder.routes().route( r->
r.path("/demo/**")
.uri("lb://demo-provider ")
.filter(new TokenGatewayFilter())
.id("demo_route ")) .build(); }}Copy the code
2. AbstractGatewayFilterFactory class inheritance
@Component
public class TokenCheckGatewayFilterFactory extends AbstractGatewayFilterFactory<TokenCheckGatewayFilterFactory.Config> {
public TokenCheckGatewayFilterFactory(a) {
super(Config.class);
}
@Override
public List<String> shortcutFieldOrder(a) {
return Arrays.asList("enabled");
}
@Override
public GatewayFilter apply(Config config) {
return (exchange, chain) -> {
system.out.println("This is where you deal with your own logic.")
return chain.filter(exchange);
};
}
public static class Config {
// Controls whether authentication is enabled
private boolean enabled = true;
public Config(a) {}
public boolean isEnabled(a) {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled; }}}Copy the code
Here we can add this filter directly to the application. Yml for the routes to be filtered.
Spring: cloud: gateway: routes: -id: demo_route # Predicates: -path =/demo/** # Asserts that filters matching paths will be routed: -tokenCheck =trueCopy the code
Note that the name of the custom filter must be XXGatewayFilterFactory, and the name of the filter in the configuration file must be XX.
Of course, we can also add this filter for each route and write the configuration directly instead of writing it for each route.
spring:
cloud:
gateway:
default-filters:
- TokenCheck=true
Copy the code
3. Implement GlobalFilter and Ordered
GlobalFilter is a GlobalFilter, as its name implies, meaning that all requests are filtered by implementing this interface and we do not need to add a filter to a route.
@Component
public class TokenGlobalFilter implements GlobalFilter.Ordered {
@Override
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
System.out.println("This is where you deal with your own logic.");
return chain.filter(exchange);
}
@Override
public int getOrder(a) {
return 0; }}Copy the code
These are the three ways to implement custom gateway filters. The actual development needs to implement the appropriate filter is ok.