gateway
Gateway functions:
-
Identity authentication and authority verification
-
Service routing and load balancing
-
Request current limiting
In spring cloud, there are two implementations of gateway:
-
gateway
-
zuul
Zuul is a Servlet based implementation and belongs to blocking programming. Spring cloud gateway is based on WebFlux provided in spring 5. It belongs to the implementation of responsive programming and has better performance.
To create a gateway service:
- Create service
- Introduce dependency
<!--gateway--> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <!--nacos Service discovery dependency--> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency>
- Write startup class
@SpringBootApplication public class GatewayApplication { public static void main(String[] args) { SpringApplication.run(GatewayApplication.class,args); } }
- Write routing configuration
server: port: 10010 # Gateway port spring: application: name: gateway # Service name cloud: nacos: server-addr: localhost:8848 # nacos address gateway: routes: # Gateway routing configuration - id: user-service # Routing id, user-defined, as long as it is unique # uri: http://127.0.0.1: the destination address of 8081 # route http is the fixed address uri: lb://The target address lb of userservice # route is load balancing, followed by the service name predicates: # Route assertion is to judge whether the request meets the conditions of routing rules - Path=/user/** # This is matched according to the path. It meets the requirements as long as it starts with / user /
Gateway construction steps:
-
Create a project and introduce nacos service discovery and gateway dependency
-
Configure application YML, including basic service information, nacos address and routing
Routing configuration includes:
-
Route id: the unique identifier of the route
-
Routing destination (uri): the destination address of the route. http represents the fixed address and lb represents load balancing according to the service name
-
Route predicates: Rules for judging routes,
-
Routing filters: process requests or responses
Route Predicate Factory
name | explain | Examples |
---|---|---|
After | Is a request after a certain point in time | - After=2037-01-20T17:42:47.789-07:00[America/Denver] |
Before | Is a request before a certain point in time | - Before=2031-04-13T15:14:47.433+08:00[Asia/Shanghai] |
Between | Is a request before two points in time | - Between=2037-01-20T17:42:47.789-07:00[America/Denver], 2037-01-21T17:42:47.789-07:00[America/Denver] |
Cookie | The request must contain some cookie s | - Cookie=chocolate, ch.p |
Header | The request must contain some header s | - Header=X-Request-Id, \d+ |
Host | The request must be to access a host (domain name) | - Host=.somehost.org,.anotherhost.org |
Method | The request method must be the specified method | - Method=GET,POST |
Path | The request path must conform to the specified rules | - Path=/red/{segment},/blue/** |
Query | The request parameter must contain the specified parameter | -Query=name, Jack or - Query=name |
RemoteAddr | The ip address of the requester must be in the specified range | - RemoteAddr=192.168.1.1/24 |
Weight | Weight processing |
Routing filter (GatewayFilterFactory)
After routing, the request sent by the user enters the filter chain, and then reaches the micro service.
The response of the microservice will also enter the filter chain first and finally return to the user.
- to configure
filters: # filter - AddRequestHeader=Truth, Itcast is freaking awesome! # Add request header
- Get (must be through the port number of gateway gateway.)
@GetMapping("/{id}") public User queryById(@PathVariable("id") Long id,@RequestHeader(value = "Truth",required = false)String truth) { System.out.println(truth); return userService.queryById(id); }
Global filter
- Implement GlobalFilter interface
- Write logic
@Order(-1)//Priority - 1, the smaller the higher @Component public class AuthorizeFilter implements GlobalFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { //1. Get request parameters ServerHttpRequest request = exchange.getRequest(); MultiValueMap<String, String> queryParams = request.getQueryParams(); //2. Get the authorize parameter in the parameter String authorize = queryParams.getFirst("authorize"); //3. Judge whether the value of this parameter is admin if("admin".equals(authorize)){ //4.1 release return chain.filter(exchange); }else{ //4.2 interception //4.2.1 set the status code type to enumeration exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED); //4.2.2 interception return exchange.getResponse().setComplete(); } } }
-
What is the function of the filter?
-
Process the request or response of the route, such as adding a request header
-
The filter configured under the route is only effective for the requests of the current route
-
-
What is the function of defaultFilters?
- Filters in effect for all routes
Filter execution sequence
-
Each filter must specify an order value of type int. the smaller the order value, the higher the priority and the higher the execution order.
-
GlobalFilter specifies the order value by implementing the Ordered interface or adding the @ order annotation, which is specified by ourselves
-
The order of routing filter and defaultFilter is specified by Spring. By default, it is incremented from 1 in the order of declaration.
-
When the order value of the filter is the same, it will be executed in the order of defaultfilter > routing filter > globalfilter.
Conclusion:
- The lower the order value, the higher the priority
- When the order value is the same, the order is defaultFilter first, then local routing filter, and finally global filter