SpringCloudAlibaba essay directory
I SpringCloudAlibaba is the father of the project
II Nacos building and service registration of spring cloud Alibaba project
III Producers and consumers of spring cloud Alibaba project
IV Ribbon load balancing of spring cloud Alibaba project
V OpenFeign remote call of spring cloudalibaba project
Vi Nacos config configuration center of spring cloud Alibaba project
VII Sentinel traffic control of spring cloud Alibaba project
VIII Seata distributed transaction of spring cloud Alibaba project
IX GateWay gateway of spring cloudalibaba project
X SkyWalking link tracking of spring cloud Alibaba project
GateWay gateway of spring cloudalibaba project
1. What is an API gateway
(1) definitions
The role of gateway is as an API architecture to protect, enhance and control access to API services. API gateway is a system before applications or services (providing REST API interface services), which is used to manage authorization, access control and traffic restrictions. In this way, REST API interface services are protected by API gateway and transparent to all callers. Therefore, the business system hidden behind the API gateway can focus on creating and managing services without dealing with these strategic infrastructure.
(2) functions
(3) classification and function
2,GateWay
(1) Introduction
Spring Cloud Gateway is a gateway officially developed by spring based on Spring 5.0, Spring Boot 2.0 and Project Reactor. Spring Cloud Gateway aims to provide a simple and effective unified API routing management method for microservice architecture. As a gateway in the Spring Cloud ecosystem, Spring Cloud Gateway aims to replace ZUUL. It not only provides a unified routing method, but also provides the basic functions of the gateway based on the Filter chain, such as security, monitoring / embedding point, and current limiting.
github: https://github.com/apex/gateway
(2) why use Gateway
Spring Cloud Gateway can be regarded as a zuul 1 The upgraded version and substitute of X uses Netty to realize asynchronous IO earlier than Zuul 2, so as to realize a simple and better implementation than zuul 1 X is a more efficient API gateway that works closely with Spring Cloud.
Spring Cloud Gateway clearly distinguishes between Router and Filter, and a great feature is that it has built-in many out of the box functions, which can be used through SpringBoot configuration or manual coding chain call.
For example, there are 10 built-in routers, so that we can directly configure them and route according to Header, Path, Host or Query at will.
For example, it distinguishes between general Filter and global Filter, and has built-in 20 kinds of filters and 9 kinds of global filters, which can also be used directly. Of course, it is also very convenient to customize the Filter.
(3) concept
3. Quick use
pom.xml dependency
<!-- nacos Service registration discovery (client) dependency --> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> <!-- gateway Gateway dependency --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
application.yml (yaml format is recommended)
# Application service WEB access port
server:
port: 8090
spring:
application:
name: service-gateway # apply name
cloud:
# Nacos help documentation: https://nacos.io/zh-cn/docs/concepts.html
# Nacos certification information
nacos:
discovery:
username: nacos
password: nacos
# Nacos service discovery and registration configuration, where the sub attribute server addr specifies the Nacos server host and port
server-addr: 127.0.0.1:8848
namespace: public # Register with the specified namespace of nacos. The default is public
# gateway configuration
gateway:
# Routing rules
routes:
- id: order_route # Unique identification of the route to order
uri: lb://Service openfeign # addresses to be forwarded lb: use the local load balancing policy of nacos
# Assertion rules are used to match routing rules
predicates:
- Path=/service-order/**
# filter
filters:
- StripPrefix=1 #Remove layer 1 routing before forwarding
Note: in yaml format, pay attention to the corresponding position of each field, otherwise there will be problems
Access address: http://127.0.0.1:8090/service-order/order/addOrder
4. Route assertion factory
(1) Built in route assertion factory
4.1,After Route Predicate Factory
Get a parameter in UTC time format from after route predict factory. When the requested current time is later than the configured UTC time, it will be matched successfully, otherwise it cannot be matched successfully.
application.yml
spring:
cloud:
gateway:
routes:
- id: after_route
uri: http://xxx.com
predicates:
- After=2021-01-20T17:42:47.789-07:00[Asia/Shanghai]
This route matches all requests after Jan 20, 2021 17:42 UTC time, and routes to uri:http://xxx.com
4.2,Before Route Predicate Factory
Get a parameter in UTC time format in before route predict factory. When the requested current time is before the configured UTC time, it will be matched successfully, otherwise it cannot be matched successfully.
application.yml
spring:
cloud:
gateway:
routes:
- id: before_route
uri: http://xxx.com
predicates:
- Before=2021-01-20T17:42:47.789-07:00[Aisa/Shanghai]
This route matches all requests before Jan 20, 2021 17:42 UTC time, and routes to uri:http://xxx.com
4.3,Between Route Predicate Factory
Get a parameter in UTC time format in the between route predict factory. When the requested current time is between the configured UTC time, it will be matched successfully, otherwise it cannot be matched successfully.
application.yml
spring:
cloud:
gateway:
routes:
- id: between_route
uri: http://xxx.com
predicates:
- Between=2021-01-20T17:42:47.789-07:00[Aisa/Shanghai], 2021-01-21T17:42:47.789-07:00[Aisa/Shanghai]
If it is in this interval, the route can be matched and accessed normally.
4.4,Cookie Route Predicate Factory
The cookie route predict factory takes two parameters (the name named "cookie" in the Header, the corresponding Key and Value). When the cookie carried by the request is consistent with the cookie assertion factory configuration, the route matching is successful, otherwise the matching fails.
spring:
cloud:
gateway:
routes:
- id: cookie_route
uri: http://xxx.com
predicates:
- Cookie=chocolate, ch.p
This route will match the request with chocolate=ch.p in the cookie
4.5,Header Route Predicate Factory
The Header Route Predicate Factory asserts the matching route according to the configured route Header information, and forwards the matching route successfully, otherwise it will not forward.application.yml
spring:
cloud:
gateway:
routes:
- id: header_route
uri: http://xxx.com
predicates:
- Header=X-Request-Id, \d+
This route will match the request with X-Request-Id in the request header and one or more numbers.
4.6,Host Route Predicate Factory
spring:
cloud:
gateway:
routes:
- id: host_route
uri: http://xxx.com
predicates:
- Host=**.somehost.org,**.anotherhost.org
This route will match the Host header of the request www.somehost.org or beta.somehost.org or www.anotherhost.org.
4.7,Method Route Predicate Factory
spring:
cloud:
gateway:
routes:
- id: method_route
uri: http://xxx.com
predicates:
- Method=GET
This route matches the request with HttpMethod of Get.
4.8,Path Route Predicate Factory
spring:
cloud:
gateway:
routes:
- id: host_route
uri: http://xxx.com
predicates:
- Path=/foo/{segment},/bar/{segment}
If there is a request address such as / foo/1 ^ or / foo/bar ^ or / bar/baz, the route will be matched.
4.9,Query Route Predicate Factory
spring:
cloud:
gateway:
routes:
- id: query_route
uri: http://xxx.com
predicates:
- Query=foo,baz
The current route will match the request whose path parameter contains foo=baz.
4.10,RemoteAddr Route Predicate Factory
spring:
cloud:
gateway:
routes:
- id: remoteaddr_route
uri: http://xxx.com
predicates:
- RemoteAddr=192.168.1.1/24
Requests with ip 192.168.1.1 ~ 192.168.1.255 at the request originator.
Reference link: https://www.jianshu.com/p/14132c18f683
(2) Custom route assertion factory
The custom route assertion factory needs to inherit the AbstractRoutePredicateFactory class and override the logic of the apply method and the shortcutFieldOrder method. In the apply method, you can use exchange Getrequest () gets the ServerHttpRequest object, so you can get the request parameters, request method, request header and other information. The parameters of the apply method are user-defined configuration classes. When using, configure the parameters and obtain them directly in the apply method. The name needs to end with RoutePredicateFactory, such as CheckAuthRoutePredicateFactory. When used, CheckAuth is the name of the route assertion factory.
CheckAuthRoutePredicateFactory
/** * Custom route assertion factory */ @Component public class CheckAuthRoutePredicateFactory extends AbstractRoutePredicateFactory<CheckAuthRoutePredicateFactory.Config> { public CheckAuthRoutePredicateFactory() { super(Config.class); System.out.println("Loaded RoutePredicateFactory [CheckAuth]"); } @Override public List<String> shortcutFieldOrder() { return Arrays.asList("name"); } /** * Custom assertion rules * @param config * @return */ @Override public Predicate<ServerWebExchange> apply(Config config) { System.out.println("Name===>:" + config.getName()); return exchange -> { if (config.getName().equals("qt")) { return true; } return false; }; } //Configure an internal class public static class Config { private String name; public void setName(String name) { this.name = name; } public String getName() { return name; } } }
application. Add routing configuration in YML
spring:
cloud:
# gateway configuration
gateway:
# Routing rules
routes:
- id: order_route # Unique identification of the route to order
uri: lb://The service name of the service openfeign # calling interface and the address to be forwarded lb: use the local load balancing policy of nacos
# Assertion rules are used to match routing rules
predicates:
- Path=/service-order/**
- CheckAuth=qt
# filter
filters:
- StripPrefix=1 #Remove layer 1 routing before forwarding
5. Filter
In addition to the request routing function, Spring Cloud Gateway also supports request filtering. Similar to Zuul gateway, it is also implemented in the form of filter.
(1) Filter life cycle
The Filter life cycle of Spring Cloud Gateway is not as rich as that of Zuul. It has only two: "pre" and "post".
PRE: this filter is called before the request is routed. We can use this filter to realize authentication, select the requested microservices in the cluster, record debugging information, etc.
POST: this filter is executed after routing to the microservice. This filter can be used to add standard HTTP} headers for responses, collect statistics and indicators, send responses from microservices to clients, and so on.
(2) filter type
The Filter of Spring Cloud Gateway can be divided into two types: GatewayFilter and GlobalFilter.
Gateway filter: applied to a single route or a packet route.
Global filter: applied to all routes.
(3) local filter
A gateway filter is a filter for a single route. The accessed URL can be filtered and processed in aspect. Many different types of local filters are built in the Spring Cloud Gateway in the form of GatewayFilter. Here, all filter factories built in Spring Cloud Gateway are simply sorted into a table. Although it is not very detailed, it can be used as a quick view. As follows:
Each filter factory corresponds to an implementation class, and the names of these classes must end with GatewayFilterFactory, which is a convention of Spring Cloud Gateway. For example, the implementation class corresponding to AddRequestHeader is AddRequestHeaderGatewayFilterFactory. These filters can be used for official reference.
(4) Global filter
The Global Filter acts on all routes. The Spring Cloud Gateway defines the Global Filter interface. Users can customize and implement their own Global Filter. The Global Filter can realize the unified verification of permissions, security verification and other functions, and the Global Filter is also a filter used by programmers.
Spring Cloud Gateway also processes the whole route forwarding through a series of built-in global filters, as follows:
In the following, we customize a GlobalFilter to verify whether the request parameters of all requests contain "token". How not to include the request parameter "token", the route will not be forwarded, otherwise the normal logic will be executed.
/** * Customize a global filter * Implement the globalfilter and ordered interfaces */ @Component public class LoginFilter implements GlobalFilter,Ordered { /** * Execute the business logic in the filter * Judge the access token in the request parameters * If this parameter exists, it means that the authentication has been successful * If this parameter does not exist: authentication failed * ServerWebExchange : Equivalent to the context of request and response (requestcontext in zuul) */ @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { System.out.println("A custom global filter was implemented"); //1.Get request parameters access-token String token = exchange.getRequest().getQueryParams().getFirst("access-token"); //2.Judge whether it exists if(token == null) { //3.If it doesn't exist : Authentication failed System.out.println("not logged on"); exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); return exchange.getResponse().setComplete(); //End of request } //4.If present,Continue execution return chain.filter(exchange); //Continue down } /** * Specifies the execution order of the filter. The smaller the return value, the higher the execution priority */ @Override public int getOrder() { return 0; } }
Reference link: https://www.cnblogs.com/dalianpai/p/12288884.html
6. Cross domain processing
There are two methods to configure cross domain processing for gateway. The configuration file is application YML and configuration class.
(1)application.yml
spring:
cloud:
gateway:
globalcors:
# Global allow cross domain access
cors-configurations:
'[/**]':
allow-credentials: true
allowed-origins: "*"
allowed-headers: "*"
allowed-methods:
- OPTIONS
- GET
- POST
- PUT
- DELETE
(2) Configuration class configuration
import org.springframework.context.annotation.Bean; import org.springframework.context.annotation.Configuration; import org.springframework.web.cors.CorsConfiguration; import org.springframework.web.cors.reactive.CorsWebFilter; import org.springframework.web.cors.reactive.UrlBasedCorsConfigurationSource; import org.springframework.web.util.pattern.PathPatternParser; @Configuration public class CorsConfig { @Bean public CorsWebFilter corsFilter() { UrlBasedCorsConfigurationSource source = new UrlBasedCorsConfigurationSource(new PathPatternParser()); source.registerCorsConfiguration("/**", buildConfig()); return new CorsWebFilter(source); } private CorsConfiguration buildConfig() { CorsConfiguration corsConfiguration = new CorsConfiguration(); //It is better to specify the domain name in the production environment to avoid cross domain security problems corsConfiguration.addAllowedOrigin("*"); corsConfiguration.addAllowedHeader("*"); corsConfiguration.addAllowedMethod("*"); return corsConfiguration; } }
7. Integrated sentinel flow control degradation