Unified GatewayGateway
Table of Contents
Unified gatewayGateway
Why do you need a gateway?
Technical implementation of gateway
Build gateway service
route assertion factory
Route filterGatewayFilter
Case: Add request header to request
GlobalFilterGlobalFilter
Define a global filter to intercept and determine user identity
Filter execution order
Gateway cross-domain problem handling
Why is a gateway
There are many services in the project that are only open to internal personnel. If all user requests can be accessed, it would be too unsafe. User requests need to be judged, and only internal personnel or staff are allowed to enter. Then the gateway is used to do this. All requests must first go to the gateway for identity authentication and then to the microservices
Gateway functions:
1. Service routing: The API gateway routes the request to the corresponding back-end service based on the requested URL path or other identifiers. Through configured routing rules, routes can be flexibly distributed to different backend services.
2. Security authentication and authorization: ensure that only authenticated requests can access services
3. Load balancing: distribute requests evenly to multiple instances to improve system throughput and scalability
4. Caching: API gateway can cache the response of the back-end service and reduce the number of requests to the service.
5. Data conversion and protocol conversion: The gateway can perform data format conversion or protocol conversion between the client and the back-end service, such as converting HTTP to WebSocket, or converting the format of the request parameters to meet the needs of the back-end service.
6. Monitoring and logging: The gateway can record request indicators and logs, providing monitoring and analysis so that developers can troubleshoot and optimize performance.
Technical implementation of gateway
The implementation of gateway in Spring Cloud includes two types
- gateway – based on WebFlux provided in Spring5, it is an implementation of reactive programming and has better performance.
- zuul – Servlet-based implementation, belonging to blocking programming.
Build a gateway service
1. Create a project and introduce nacos service discovery and gateway dependencies
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>com.alibaba.cloud</groupId> <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId> </dependency> </dependencies>
2. Configure application.yml, including basic service information, nacos address, and routing
Routing configuration includes
1. Route id: the unique identifier of the route
2. Routing target (uri): the target address of the route, http represents a fixed address, and lb represents load balancing based on the service name.
3. Routing assertions (predicates): rules for determining routing
4. Routing filters: Process requests or responses
server: port: 10010 # Gateway port spring: application: name: gateway # Service name cloud: nacos: server-addr: localhost:8848 #nacos address gateway: routes: - id: user-service # Routing id, customized, as long as it is unique # uri: http://127.0.01:8081 #The destination address of the route. This way of writing is not recommended. uri: lb://userservices # The destination address of the route. Lb is the load balancing, followed by the service name. predicates: #Routing assertion, that is, determining whether the request meets the conditions of routing rules - Path=/user/** # If the request sent conforms to this rule /user/, then the userservice will be accessed through this route - id: order-service uri: lb://orderservices predicates: - Path=/order/**
Route assertion factory
The role of route assertion factory
Read the assertion rules configured by the user, then parse them into corresponding judgment conditions, and conduct rule judgment on the user’s request.
Routing filter GatewayFilter
GatewayFilter is a filter provided in the gateway, which can process gateway requests and microresponses returned by microservices:
Case: Add request header to request
Add a request header to all requests entering userservice: Truth=zstc is freaking awesome!
Implementation method: Modify the application.yml file in the gateway and add filters to the userservice route.
Get the request header in UserController, and use the annotation @RequestHeader annotation to get the parameters spring will automatically get from the request header.
If you want to add filters to all requests, you can configure default-filters:
Global FilterGlobalFilter
The difference from the previous two filters:
GatewayFilter is defined through configuration. The business logic of the filter is fixed by spring and cannot be controlled. However, some business logic is more complex. For example, if a request comes in, you want to know who initiated the request and whose identity it is. What, this cancustomize the business logic of the interceptor through GlobalFilter.
The way to define it is to implement the GlobalFilter interface:
Chain is a filter chain. Its function is to release the filter. After the filter logic is processed, it is handed over to the next filter.
Define a global filter to intercept and determine user identity
Determine whether the parameter contains authorization and whether the authorization parameter value is admin
//@Order is an order annotation. To give an Int value, order is used to define the priority when there are multiple filters. @Order(-1) @Component public class AuthorizeFilter implements GatewayFilter { @Override public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) { //1. Get request parameters ServerHttpRequest request = exchange.getRequest(); //2. Get the authorization parameter in the parameter MultiValueMap<String, String> queryParams = request.getQueryParams(); String authorization = queryParams.getFirst("authorization"); //3. Determine whether the parameter value is admin if (authorization.equals("admin")){ //4.Yes, release //Here is actually the next interceptor call and its filter method in the chain of responsibility. return chain.filter(exchange); } //5.No, intercept //5.1.Set status code ServerHttpResponse response = exchange.getResponse(); response.setStatusCode(HttpStatus.UNAUTHORIZED); //5.2. Interception request return response.setComplete(); } }
Filter execution order
- 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
- The order values of routing filters and default filters are specified by spring. By default, they increase from 1 in the order of declaration.
- When the order values of the filters are the same, the execution order is Default filter>Routing filter>GlobalFilter
Gateway cross-domain problem handling
What is cross-domain?
Under the restriction of the browser’s same-origin policy, if an XHR request is sent to different sources (different protocols, different port numbers, different domain names), the browser will consider the request to be untrusted and prohibit the request.
In microservices, cross-domain requests do not need to be processed in each microservice, they only need to be processed uniformly in the gateway.
Learning materials from Dark Horse Programmer