Microservice_Service Gateway (Gateway)

Table of contents

1. Why do you need a gateway

2. Implementation of Spring Cloud Gateway

3. Gateway practice

1) Create a gateway service and introduce dependencies

2) Write the startup class

3) Write basic configuration and routing rules

4) Restart the test

5) Flow chart of gateway routing

4. Assertion Factory

5. Filtration factory

1) Types of routing filters

2) Request header filter

3) Default filter

4) Summary

6. Global filtering

1) Definition

2) case

3) Filter execution order

7. Cross-domain issues

1) What is a cross-domain problem

2) Solve cross-domain problems


1. Why do you need a gateway

     Gateway is the gatekeeper of our services, the unified entrance of all microservices. Different microservices generally have different network addresses, and external clients may need to call multiple service interfaces to fulfill a business requirement. If the client directly communicates with each microservice, there will be the following problems:

  1. The client will request different microservices multiple times, increasing the complexity of the client
  2. There are cross-domain requests, and the processing is relatively complicated in certain scenarios
  3. Authentication is complex, each service requires independent authentication
  4. It is difficult to refactor, and as the project iterates, it may be necessary to re-partition microservices. For example, it is possible to merge multiple services into one or to split one service into several. If clients communicate directly with microservices, refactoring will be difficult to implement
  5. Some microservices may use firewall/browser-unfriendly protocols, and direct access will be difficult

The above problems can be solved with the help of the gateway, so the gateway mainly has the following characteristics:

  1. Access control: As the entry point of microservices, the gateway needs to verify whether the user is eligible for the request, and intercept it if not.
  2. Routing and load balancing: All requests must first pass through the gateway, but the gateway does not process business, but forwards the request to a microservice according to certain rules. This process is called routing. Of course, when there are multiple target services for routing, load balancing is also required.
  3. Current limiting: When the request traffic is too high, the gateway will release the request according to the speed that the downstream microservice can accept, so as to avoid excessive service pressure.

2. Implementation of Spring Cloud Gateway

  • gateway
  • zul

Zuul is a Servlet-based implementation and belongs to blocking programming. Spring Cloud Gateway is based on WebFlux provided in Spring 5, which is an implementation of responsive programming and has better performance.

3. Gateway practice

The basic steps to build a Gateway are as follows:

  1. Create a SpringBoot project gateway and introduce gateway dependencies
  1. Write startup class
  1. Write basic configuration and routing rules
  1. Start the gateway service for testing

1 ) Create a gateway service and introduce dependencies

Create a service:

Import dependencies:

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

2 ) Write the startup class

TypeScript
package cn.itcast.gateway;
 
import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
 
@SpringBootApplication
public class GatewayApplication {
 
    public static void main(String[] args) {
        SpringApplication.run(GatewayApplication.class, args);
    }
}

3 ) Write basic configuration and routing rules

Create an application.yml file with the following content:

Bash
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 # Route id , custom, as long as it is unique
          # uri: http://127.0.0.1:8081 # The target address http of the route is a fixed address
          uri: lb://userservice # The target address lb of the route is load balancing, followed by the service name
          predicates: # Routing assertion, that is, the condition for judging whether the request meets the routing rules
            - Path=/user/** # This is matched according to the path, as long as it starts with /user/, it meets the requirements

We will proxy all requests that match the Path rule to the address specified by the uri parameter.

In this example, we proxy the request starting with /user/** to lb://userservice, lb is load balancing, and pull the service list according to the service name to achieve load balancing.

4 ) Restart the test

重启网关,访问http://localhost:10010/user/1时,符合/user/**规则,请求转发到uri:http://userservice/user/1,得到了结果:

5)网关路由的流程图

整个访问的流程如下:

总结:

  1. 网关搭建步骤:
  2. 创建项目,引入nacos服务发现和gateway依赖
  3. 配置application.yml,包括服务基本信息、nacos地址、路由
  4. 路由配置包括:
  • 路由id:路由的唯一标示
  • 路由目标(uri):路由的目标地址,http代表固定地址,lb代表根据服务名负载均衡
  • 路由断言(predicates):判断路由的规则,
  • 路由过滤器(filters):对请求或响应做处理

四、断言工厂

我们在配置文件中写的断言规则只是字符串,这些字符串会被Predicate Factory读取并处理,转变为路由判断的条件例如Path=/user/**是按照路径匹配,这个规则是由

org.springframework.cloud.gateway.handler.predicate.PathRoutePredicateFactory类来处理的,像这样的断言工厂在SpringCloudGateway还有十几个:

五、过滤工厂

 GatewayFilter是网关中提供的一种过滤器,可以对进入网关的请求和微服务返回的响应做处理:

1)路由过滤器的种类

Spring提供了31种不同的路由过滤器工厂。例如:

2)请求头过滤器

下面我们以AddRequestHeader 为例来讲解。

需求:给所有进入userservice的请求添加一个请求头:Test=This is a test!

只需要修改gateway服务的application.yml文件,添加路由过滤即可:

Bash
spring:
  cloud:
    gateway:
      routes:
      - id: user-service
        uri: lb://userservice
        predicates:
        - Path=/user/**
        filters: #
过滤器
        - AddRequestHeader=Test,This is a test! # 添加请求头

当前过滤器写在userservice路由下,因此仅仅对访问userservice的请求有效。

3)默认过滤器

如果要对所有的路由都生效,则可以将过滤器工厂写到default下。格式如下:

Bash
spring:
  cloud:
    gateway:
      routes:
      - id: user-service
        uri: lb://userservice
        predicates:
        - Path=/user/**
      default-filters: #
默认过滤项
      - AddRequestHeader=Test,This is a test! # 添加请求头   

4)总结

过滤器的作用是什么?

① 对路由的请求或响应做加工处理,比如添加请求头

② 配置在路由下的过滤器只对当前路由的请求生效

defaultFilters的作用是什么?

① 对所有路由都生效的过滤器

六、全局过滤

1)定义

上一章节讲的过滤器,网关提供了31种,但每一种过滤器的作用都是固定的。如果我们希望拦截请求,做自己的业务逻辑则没办法实现。而全局过滤器刚好可以解决这个问题,GlobalFilter的逻辑需要自己写代码实现,定义方式是实现GlobalFilter接口。

Java
public interface GlobalFilter {
    /**
     * 
处理当前请求,有必要的话通过{@link GatewayFilterChain}将请求交给下一个过滤器处理
     *
     * @param exchange 请求上下文,里面可以获取Request、Response等信息
     * @param chain 用来把请求委托给下一个过滤器
     * @return {@code Mono<Void>} 返回标示当前过滤器业务结束
     */
    Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain);
}

在filter中编写自定义逻辑,可以实现下列功能:

  • 登录状态判断
  • 权限校验
  • 请求限流等

2)案例

需求:定义全局过滤器,拦截请求,判断请求的参数是否满足下面条件:

  • 参数中是否有authorization
  • authorization参数值是否为admin
  • 如果同时满足则放行,否则拦截

TypeScript
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.
获取请求参数
        MultiValueMap<String, String> params = exchange.getRequest().getQueryParams();
        // 2.获取authorization参数
        String auth = params.getFirst("authorization");
        // 3.校验
        if ("admin".equals(auth)) {
            // 放行
            return chain.filter(exchange);
        }
        // 4.拦截
        // 4.1.禁止访问,设置状态码
        exchange.getResponse().setStatusCode(HttpStatus.FORBIDDEN);
        // 4.2.结束处理
        return exchange.getResponse().setComplete();
    }
}

3)过滤器执行顺序

请求进入网关会碰到三类过滤器:当前路由的过滤器、DefaultFilter、GlobalFilter,请求路由后,会将当前路由过滤器和DefaultFilter、GlobalFilter,合并到一个过滤器链(集合)中,排序后依次执行每个过滤器:

排序的规则是什么呢?

  1. 每一个过滤器都必须指定一个int类型的order值,order值越小,优先级越高,执行顺序越靠前。
  2. GlobalFilter通过实现Ordered接口,或者添加@Order注解来指定order值,由我们自己指定
  3. 路由过滤器和defaultFilter的order由Spring指定,默认是按照声明顺序从1递增。
  4. 当过滤器的order值一样时,会按照 defaultFilter > 路由过滤器 > GlobalFilter的顺序执行。

详细内容,可以查看源码:

org.springframework.cloud.gateway.route.RouteDefinitionRouteLocator#getFilters()方法是先加载defaultFilters,然后再加载某个route的filters,然后合并。

org.springframework.cloud.gateway.handler.FilteringWebHandler#handle()方法会加载全局过滤器,与前面的过滤器合并后根据order排序,组织过滤器链

七、跨域问题

1)什么是跨域问题

跨域:域名不一致就是跨域,主要包括:

  • 域名不同: www.taobao.com 和 www.taobao.org 和 www.jd.com 和 miaosha.jd.com
  • 域名相同,端口不同:localhost:8080和localhost8081

跨域问题:浏览器禁止请求的发起者与服务端发生跨域ajax请求,请求被浏览器拦截的问题

解决方案:CORS,不知道的小伙伴可以查看https://www.ruanyifeng.com/blog/2016/04/cors.html

2)解决跨域问题

在gateway服务的application.yml文件中,添加下面的配置:

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

Guess you like

Origin blog.csdn.net/wanghaiping1993/article/details/129887501