This is the 14th day of my participation in Gwen Challenge
Gateway
An overview,
The Gateway provides a simple and efficient way to route apis, as well as some powerful filtering functions, such as fusing, streaming, retry, and so on.
Spring Cloud Gateway, as the Gateway in the Spring Cloud ecosystem, aims to replace Zuul. Cloud Gateway is implemented based on WebFlux framework. The bottom layer of The Web Flux framework uses the high performance Reactor pattern communication framework Netty, which is developed based on the asynchronous non-blocking model.
The Spring Cloud Gateway provides a unified routing mode and provides basic Gateway functions, such as security, monitoring, indicators, and traffic limiting, based on Filter chain.
Gateway three concepts:
- Route: The basic module that makes up a gateway. It consists of an ID, a destination URL, a set of assertions, and filters that match the Route if the assertion is true.
- Predicate: Matches everything in an Http request, and routes the request if it matches the Predicate.
- Filter: With filters, requests can be modified before or after routing.
The client sends a request to the Gateway. How to find the route matching the request in the Gateway Handler Mapping and send the route to the Gateway Web Handler? The Handler then sends the request through the specified filter chain to the actual server to perform the business logic, how to return. You can perform parameter verification, permission verification, traffic monitoring, log output, and protocol conversion on the pre-filter. The post-filter can modify the response content and response header.
Second, build the environment
Note: You cannot add web dependencies after gateway is introduced
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
Copy the code
Configuration file Configures routing rules
server:
port: 9527
eureka:
client:
register-with-eureka: true
fetch-registry: true
service-url:
defaultZone: http://eureka7001.com:7001/eureka
spring:
application:
name: cloud-gateway
cloud:
gateway:
routes: You can configure multiple routes
- id: payment_routh # route ID, no fixed rule but unique, recommend with service name
uri: http://localhost:8001 # Route address to provide service after match
predicates:
- Path=/payment/getById/** # assert that the path matches the route
- id: payment_routh2
uri: http://localhost:8001
predicates:
- Path=/payment/getPort/**
Copy the code
test
Visit http://localhost:9527/payment/getById/ * * can access to 8001 access method.
Or configure routing rules in coding mode
/** * Configure the gateway route using the config class method */
@SpringBootConfiguration
public class GatewayConfig {
/ * * * is configured with a routing name for path_route_yylm rules news domestic news * * http://localhost:9527/guonei jump to baidu@param builder
* @return* /
@Bean
public RouteLocator routes(RouteLocatorBuilder builder) {
RouteLocatorBuilder.Builder routes = builder.routes();
routes.route("path_route_yylm",r -> r.path("/guonei").uri("http://news.baidu.com/guonei")).build();
returnroutes.build(); }}Copy the code
Dynamic routing
The Gateway gateway is also registered in the registry, and specific services are invoked by the microservice name in the registry.
configuration
gateway:
discovery:
locator:
enabled: true Use the service name of the registry for routing
routes:
- id: payment_routh # route ID, no fixed rule but unique, recommend with service name
uri: lb://CLOUD-PAYMENT-SERVICE Use dynamic routing to provide the service name
Copy the code
Enable 8001 and 8002 microservices to access specific services through lb:// cloud-payment-service and achieve load balancing.
Use of Predicate
Gateway includes a number of built-in Route Predicate factories, all of which match the different properties of the Http request. Predicate implements a set of matching rules that allow the request to find a Route to match
Time scale
predicates:
- Path=/payment/getPort/**
- After = 2020-12-04 T00:14:13. 512 + 08:00 Asia/Shanghai # Valid after specified time
# - Before=2020-12-04T00:10:13.512+08:00[Asia/Shanghai] #
Copy the code
Cookie level
predicates:
- Path=/payment/getPort/**
- After = 2020-12-04 T00:14:13. 512 + 08:00 Asia/Shanghai # Valid after specified time
# - Before=2020-12-04T00:14:13.512+08:00[Asia/Shanghai] #
- Cookie=username,yylm You must carry the specified cookie
Copy the code
Cookie Route Predicates require two parameters, one is Cookie name and the other is regular expression. Routing rules are matched by Cookie name and regular expression.
You must carry the Cookie value username=yylm when accessing
Header/Host Route Predicates can be accessed successfully with the specified headers.
Other levels
- Method: – Method=GET // Specifies the matching access Method
- Path: – Path= XXXX // Specify a matching access Path
- Query: -query =username, \d+ // Specifies that the parameter name must have username and the value must be an integer to route
5. Gateway Filter
A routing filter can modify the incoming HTTP request and the returned HTTP response. A routing filter can only be used by specified routes and has multiple built-in routing filters.
Built-in filters, similar to Predicates, use more custom filters.
filters:
- AddRequestHeader=X-Request-red, blue
Copy the code
Custom global filters
@Component
public class MyLogGatewayFilter implements GlobalFilter.Ordered {
public static final Logger LOGGER = LoggerFactory.getLogger(MyLogGatewayFilter.class);
public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
LOGGER.info("Enter the filter method of MyLogGatewayFilter:"+ new Date());
// Get the request parameters from the request
String name = exchange.getRequest().getQueryParams().getFirst("uname");
// Prompt if this parameter is not present
if (name == null) {
LOGGER.info("Illegal user");
exchange.getResponse().setStatusCode(HttpStatus.NOT_ACCEPTABLE);
return exchange.getResponse().setComplete();
}
return chain.filter(exchange);
}
public int getOrder(a) {
return 0; }}Copy the code
Test: use http://localhost:9527/payment/getById/31? Uname =lm, with the request parameter uname can be requested. Otherwise rejected.