当前位置:网站首页>Gateway service gateway

Gateway service gateway

2022-06-10 17:33:00 itmkyuan

Why do I need a gateway ?

Gateway function :

  • Authentication and authority verification
  • Service routing 、 Load balancing
  • Request current limiting

stay SpringCloud The implementation of gateway in includes two methods :

  • gateway
  • zuul

Zuul Is based on Servlet The implementation of the , It belongs to blocking programming . and SpringCloudGateway Is based on Spring5 Provided in WebFlux, It belongs to the implementation of responsive programming , Better performance .

Steps of building gateway service :

1. Create a new module, introduce SpringCloudGateway Dependence and nacos Dependency of service discovery :

<!-- gateway -->
<dependency>
    <groupId>org.springframework.cloud</groupId>
    <artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!--nacos Service discovery depends on -->
<dependency>
    <groupId>com.alibaba.cloud</groupId>
    <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>

2. Write routing configuration and nacos Address

server:
  port: 10010 #  Gateway port 
spring:
  application:
    name: gateway #  The service name 
  cloud:
    nacos:
      server-addr: localhost:8001 # nacos Address 
      discovery:
        namespace: c072b17e-a5a6-4c23-aff3-aa83749eefa0
    gateway:
      routes: #  Gateway routing configuration 
        - id: user-service #  route id, Customize , As long as it's the only one 
          # uri: http://127.0.0.1:8081 #  The destination address of the route  http It's a fixed address 
          uri: lb://userservice #  The destination address of the route  lb It's load balancing , Followed by the service name 
          predicates: #  Route assertion , That is, judge whether the request meets the conditions of routing rules 
            - Path=/user/** #  This is matched according to the path , As long as /user/ Meet the requirements at the beginning 
        - id: order-service
          uri: lb://orderservice
          predicates:
            - Path=/order/**

Build gateway service :

Gateway building steps :
1. Create project , introduce nacos Service discovery and gateway rely on
2. To configure application.yml, Including basic service information 、nacos Address 、 route
Routing configuration includes :
1. route id: The unique identifier of the route
2. Routing destination (uri): The destination address of the route ,http Represents a fixed address ,lb Represents load balancing based on service name
3. Route assertion (predicates): Rules for judging routing
4. Routing filter (filters): To process a request or response

Route assertion factory Route Predicate Factory

The assertion rules we write in the configuration file are just strings , These strings will be Predicate Factory Read and process , The condition for changing to routing judgment

for example Path=/user/** Is to match according to the path , This rule is made by

org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory Class to handle

Spring Provides 11 Species basic Predicate factory :

PredicateFactory What is the role of
Read user-defined assertion conditions , Judge the request
Path=/user/** What does it mean
The path is user The beginning is considered to be consistent

Routing filter GatewayFilter

GatewayFilter It is a filter provided in the gateway , Can enter Gateway request and The response returned by the microservice Do the processing :

Spring Provides 31 There are different routing filter factories . for example :

Give everyone access userservice Add a request header to your request :Truth=itcast is freaking awesome!

Realization way : stay gateway Revision in China application.yml file , to userservice Add filter for route :

spring:
  cloud:
    gateway:
      routes:
      - id: user-service 
        uri: lb://userservice 
        predicates: 
        - Path=/user/** 
        filters: #  filter 
        - AddRequestHeader=Truth, Itcast is freaking awesome! #  Add request header 

If you want to be effective for all routes , The filter factory can be written to default Next . The format is as follows :

spring:
  cloud:
    gateway:
      routes:
      - id: user-service 
        uri: lb://userservice 
        predicates: 
        - Path=/user/**
      default-filters: #  Default filter 
      - AddRequestHeader=Truth, Itcast is freaking awesome! 

What is the function of the filter ?
① Process the routed request or response , For example, add request headers
② The filter configured under the route is only effective for the requests of the current route
defaultFilters What is the role of ?
① Filters in effect for all routes

Global filter

The global filter is also used to handle all requests and microservice responses entering the gateway , And GatewayFilter It does the same thing .
The difference lies in GatewayFilter Defined by configuration , The processing logic is fixed . and GlobalFilter You need to write your own code to implement your logic .
The definition is to implement GlobalFilter Interface .

public interface GlobalFilter {
    
    /** *  Process the current request , If necessary, through {@link GatewayFilterChain} Pass the request to the next filter  * * @param exchange  Request context , You can get Request、Response Etc  * @param chain  Used to delegate the request to the next filter  * @return {@code Mono<Void>}  Return to indicate the end of the current filter business  */
    Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain);
}

Define global filters , Intercept and determine the user's identity
demand : Define global filters , Intercept request , Judge whether the requested parameters meet the following conditions :

  • Whether there is authorization,

  • authorization Whether the parameter value is admin

If both are met, release , Otherwise intercept

Custom filter

Custom class , Realization GlobalFilter Interface , add to @Order annotation :

package cn.itcast.gateway.filters;

import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter {
    
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
    
        // 1. Get request parameters 
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
        // 2. obtain authorization Parameters 
        String auth = params.getFirst("authorization");
        // 3. check 
        if ("admin".equals(auth)) {
    
            //  release 
            return chain.filter(exchange);
        }
        // 4. Intercept 
        // 4.1. Blocking access , Set status code 
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        // 4.2. End processing 
        return exchange.getResponse().setComplete();
    }
}

What is the role of the global filter ?
① Filters in effect for all routes , And you can customize the processing logic
Steps to implement the global filter ?
① Realization GlobalFilter Interface
② add to @Order To annotate or implement Ordered Interface
③ Write processing logic

Filter execution order

The request to enter the gateway will encounter three types of filters : Filter for the current route 、DefaultFilter、GlobalFilter
After request routing , The current route filter and DefaultFilter、GlobalFilter, Merge into a filter chain ( aggregate ) in , After sorting, execute each filter in turn

What are the sorting rules ?

  • Each filter must specify a int Type of order value ,order The smaller the value. , The higher the priority , The higher the order of execution .
  • GlobalFilter By implementing Ordered Interface , Or add @Order Note to specify order value , It's up to us to designate
  • Routing filters and defaultFilter Of order from Spring Appoint , The default is from... In the order of declaration 1 Increasing .
  • When the filter order When the value is the same , According to defaultFilter > Routing filter > GlobalFilter Sequential execution .

The detailed content , You can check the source code :

org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator#getFilters() The method is to load defaultFilters, Then load a route Of filters, Then merge .

org.springframework.cloud.gateway.handler.FilteringWebHandler#handle() Method loads the global filter , Combined with the previous filter, according to order Sort , Organize the filter chain

Routing filter 、defaultFilter、 The execution order of the global filter ?
① order The smaller the value. , The higher the priority
② When order When the value is the same , The order is defaultFilter The first , Then there is the local routing filter , Finally, the global filter

Cross domain problem handling

Cross domain : Domain name inconsistency is cross domain , It mainly includes :

  • Domain name is different : www.taobao.com and www.taobao.org and www.jd.com and miaosha.jd.com

  • Domain name is the same , Different ports :localhost:8080 and localhost8081

Cross-domain problem : browser The originator of the prohibition request and Cross domain on the server ajax request , The request is blocked by the browser

Solution :CORS
The gateway handles cross domain transactions in the same way CORS programme , And it only needs simple configuration to realize :

spring:
  cloud:
    gateway:
      # ...
      globalcors: #  Global cross domain processing 
        add-to-simple-url-handler-mapping: true #  solve options The request is blocked 
        corsConfigurations:
          '[/**]':
            allowedOrigins: #  Allow cross domain requests for which websites  
              - "http://localhost:8090"
            allowedMethods: #  Allowed cross domain ajax Request method of 
              - "GET"
              - "POST"
              - "DELETE"
              - "PUT"
              - "OPTIONS"
            allowedHeaders: "*" #  Header information allowed to be carried in the request 
            allowCredentials: true #  Is it allowed to carry cookie
            maxAge: 360000 #  The validity period of this cross domain detection 

CORS Which parameters should be configured across domains ?
① Which domain names are allowed to cross domains ?
② Which request headers are allowed ?
③ What kind of requests are allowed ?
④ Is it allowed to use cookie?
⑤ How long is the validity period ?

Thank you for your participation

Video address :https://www.bilibili.com/video/BV1LQ4y127n4?p=35

原网站

版权声明
本文为[itmkyuan]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/161/202206101636338737.html