spring cloud学习笔记 微服务网关Gateway

  随着技术的更新,zuul技术已经逐渐被淘汰,取而代之的是功能更加强大的Gateway 网关服务,Gateway 是基于spring 的网关项目,集成断路器,路径重写 ,还能无缝衔接到基于spring cloud的微服务开发中来。本篇博客就来介绍下Gateway 的主要使用。

一、微服务网关的优点

1、安全,提供了统一的访问入口,当有黑客攻击服务器时,能降低了服务器受攻击面积。

2、提供了统一跨域解决方案。

3、提供了统一日志记录操作,可以对微服务进行统一监控。

4、提供了统一权限认证支持。

5、提供了微服务限流功能,可以保护微服务。

总结:微服务网关的作用,就是整合各个微服务功能,形成一套或多套系统。

 

 微服务网关流程图

二、Gateway的Maven

        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-starter-gateway</artifactId>
        </dependency>

三、Gateway跨域配置

  Gateway跨域配置只需要在application中配置一段代码即可

spring:
  cloud:
    gateway:
      globalcors:
        cors-configurations:
          '[/**]': # 匹配所有请求
              allowedOrigins: "*" #跨域处理 允许所有的域
              allowedMethods: # 支持的方法
                - GET
                - POST
                - PUT
                - DELETE

四、网关路由配置

1、host路由

  host路由配置和跨域类似,只需要在application中配置一段代码即可

  下面配置所有以127.0.0.1的请求,都交给http://localhost:8080 处理

spring:
  cloud:
    gateway:
         routes:
        #id为定义的路由名称
- id: user_server_rout
        #目的地地址 uri: http:
//localhost:8080 predicates:
        #路由地址
- Host=127.0.0.1

2、路径匹配过滤配置

我们还可以根据请求路径实现对应的路由过滤操作,例如请求中以/test/路径开始的请求,都直接交给http://localhost:8080服务处理,如下配置:

spring:
  cloud:
    gateway:
        routes:
            - id: user_server_rout
              uri: http://localhost:8080
              predicates:
              - Path=/test/**            

3、PrefixPath 过滤配置

  用户每次请求路径的时候,我们可以给真实请求加一个统一前缀,例如用户请求http://localhost:8080的时候我们让它请求真实地址http://localhost:8001/test,如下配置

spring:
  cloud:
    gateway:
        routes:
            - id: user_server_rout
              uri: http://localhost:8080
              predicates:
              - Path=/**
              filters:
              - PrefixPath=/brand 

4、StripPrefix 过滤配置

   StripPrefix 能够帮我们去调用户请求中的虚拟路径,如 api/test 的请求过滤成 /test 请求,如下配置:

spring:
  cloud:
    gateway:
        routes:
            - id: user_server_rout
              uri: http://localhost:8080
              predicates:
              - Path=/**
              filters:
              #1表示去调请求路径中的1段路径
              - StripPrefix=1        

5、LoadBalancerClient 路由过滤器(客户端负载均衡)

  除开上面两个过滤器外,gateway还为我们提供了负载均衡的路由 LoadBalancerClientFilter。LoadBalancerClientFilter会作用在url以lb开头的路由,然后利用loadBalancer来获取服务实例,构造目标requestUrl,设置到GATEWAY_REQUEST_URL_ATTR属性中,供NettyRoutingFilter使用。配置如下:

spring:
  cloud:
    gateway:
        routes:
            - id: user_server_rout
               #所有请求都交给test_server服务去处理
               uri: lb://test_server
              predicates:
              - Path=/**
              filters:
              #1表示去调请求路径中的1段路径
              - StripPrefix=1              

 

posted @ 2021-07-04 17:10  想去天空的猫  阅读(435)  评论(0编辑  收藏  举报