Microservice-GateWay (gateway)

What does the so-called gateway mean?

       It is equivalent to the security guard of your community. You must obtain the consent of the security guard to enter and exit the community to protect the life and property health of your community. The same is true for the gateway, which strictly controls every request and sends legal or authorized requests to the server.

The function of the gateway:

  • Authentication and authorization verification
  • Service routing, load balancing
  • request throttling

 The common common gateways are:

Gateway: Based on WebFlux provided in Spring5, it belongs to the implementation of responsive programming and has better performance

zuul: servlet-based implementation, which belongs to blocking programming

Build gateway service

1. Create a new module and introduce the dependency of SpringCloudGateway and the service discovery dependency of nacos:

   <!--nacos服务注册发现依赖-->
        <dependency>
            <groupId>com.alibaba.cloud</groupId>
            <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
        </dependency>
        <!--网关gateway依赖-->
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

2. Write the routing configuration that is the nacos address:

server:
  port: 10010
logging:
  level:
    cn.itcast: debug
  pattern:
    dateformat: MM-dd HH:mm:ss:SSS
spring:
  application:
    name: gateway
  cloud:
    nacos:
      server-addr: nacos:8848 # nacos地址
    gateway:
      routes:
        - id: user-service # 路由标示,必须唯一
          uri: lb://userservice # 路由的目标地址
          predicates: # 路由断言,判断请求是否符合规则
            - Path=/user/** # 路径断言,判断路径是否是以/user开头,如果是则符合

Summarize:

Steps to build the gateway:

1. Create a project and introduce nacos service discovery and gateway dependencies

2. Configure application.yml, including basic service information, nacos address, routing

Routing configuration includes:

1. Reason id: the unique identifier of the route

2. Routing destination: the destination address of the routing, http stands for fixed address, lb stands for load balancing based on service name

3 Routing assertion: rules for judging routing

4. Route filter: process the request or response

Route Predicate Factory

The content that can be configured for gateway routing is:

  • route id: the unique identifier of the route
  • uri: routing destination, supports both lb and http
  • predicates: Routing assertion, to judge whether the request meets the requirements, if it meets the request, it will be forwarded to the routing destination

       The rules in the configuration file are just strings. These strings will be read and processed by the Predicate Factory, and converted into conditions for routing judgments. For example, "Path=/user/**" is matched according to the path, and only those starting with /user are allowed. considered to be consistent with

  • filter: route filter, processing request or response

11 types of factories:

 Route filter GatewayFilter

GatewayFilter is a filter provided in the gateway, which can process the requests entering the gateway and the responses returned by microservices

 Here are a few different route filter factories provided by Spring:

Now it is required to add a request header to all requests entering the A service, how would you implement it?

Add request headers to a service individually:

spring:
  cloud:
    gateway:
      routes:#网关路由配置
        - id: order-service
          uri: lb://orderservice
          predicates:
            - Path=/order/**
          filters: #过滤器
           - AddRequestHeader=Truth,Itcast is freaking awesome!#添加请求头

If you want to take effect for all routes, you can write the filter factory under default, such as:

spring:
  application:
    name: gateway
  cloud:
    nacos:
      server-addr: nacos:8848 # nacos地址
    gateway:
      routes:
        - id: user-service # 路由标示,必须唯一
          uri: lb://userservice # 路由的目标地址
          predicates: # 路由断言,判断请求是否符合规则
            - Path=/user/** # 路径断言,判断路径是否是以/user开头,如果是则符合
        - id: order-service
          uri: lb://orderservice
          predicates:
            - Path=/order/**
      default-filters:#对所有的路由都生效的过滤器
        - AddRequestHeader=Truth,Itcast is freaking awesome!

global filter

       The role of the global filter is to process all gateway requests and microservice responses. It is the same as the role of the GatewayFilter. The difference is that the GatewayFilter is defined through configuration and the processing logic is fixed, while the logic of the GlobalFilter needs to be implemented by writing code yourself. The definition is to implement the GlobalFilter interface.

//@Order(-1)
@Component
public class AuthorizeFilter implements GlobalFilter, Ordered {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1.获取请求参数
        ServerHttpRequest request = exchange.getRequest();
        MultiValueMap<String, String> params = request.getQueryParams();
        // 2.获取参数中的 authorization 参数
        String auth = params.getFirst("authorization");
        // 3.判断参数值是否等于 admin
        if ("admin".equals(auth)) {
            // 4.是,放行
            return chain.filter(exchange);
        }
        // 5.否,拦截
        // 5.1.设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.UNAUTHORIZED);
        // 5.2.拦截请求
        return exchange.getResponse().setComplete();
    }

    @Override
    public int getOrder() {
        return -1;
    }

step:

1. Implement the GlobalFilter interface

2. Add the @Order annotation or implement the Ordered interface

3. Write processing logic

filter execution order

  •  Each filter must specify an int type order value, 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 of routing filters and defaultFilter is specified by Spring, and the default is to increase from 1 according to the declaration order
  • When the order value of the filter is the same, it will be executed in the order of defaultFilter>local routing filter>GlobalFilter

cross-domain issues

       Cross-domain issues: Inconsistent domain names are cross-domain. The browser prohibits the initiator of the request from making a cross-domain ajax request with the server, and the request is intercepted by the browser

CORS:

spring:
  application:
    name: gateway
  cloud:
    nacos:
      server-addr: nacos:8848 # nacos地址
    gateway:
      globalcors: #全年的跨域处理
        add-to-simple-url-handler-mapping: true #解决options请求被拦截问题
        corsconfigurations: 
          '[/**]':
            allowedOrigins: #允许哪些网站的跨域请求
              -"http://127.0.0.1:8090"
            allowedMethods: #允许的跨域ajax的请求方式
              -"GET"
            -"POST"
            -"DELETE"
            -"PUT"
            -"OPTIONS"
            allowedHeaders: "*" #允许在请求中携带的头信息
                allowCredentials: true #是否允许携带cookie
            maxAge: 360000 #这次跨域检测的有效期

Guess you like

Origin blog.csdn.net/dfdbb6b/article/details/132342456