你必须会的微服务之Gateway网关

228 阅读4分钟

一起养成写作习惯!这是我参与「掘金日新计划 · 4 月更文挑战」的第3天,点击查看活动详情

微服务已经成当前各大大厂追求的主流技术架构,学习微服务前景非常可观,而SpringCloud已成为主流微服务技术栈。本系列文章将以SpringCloud技术栈进行精讲,全方位剖析讲解SpringCloud技术栈在微服务场景下的实战应用,可以点赞关注,后续持续为大家更新。

Spring Cloud Gateway

知识索引

  • Gateway简介
  • 入门案例
  • 路由前缀
  • 过滤器

1 Gateway简介

Spring Cloud GatewaySpring Cloud团队的一个全新项目,基于Spring 5.0SpringBoot2.0Project Reactor 等技术开发的网关。旨在为微服务架构提供一种简单有效统一的REST请求路由管理方式。

Spring Cloud Gateway 作为SpringCloud生态系统中的网关,目标是替代Netflix ZuulGateway不仅提供统一路由方式,并且基于Filter链的方式提供网关的基本功能。例如:安全,监控/指标,和限流。

2 入门案例

spring_cloud_demos项目中创建gateway_demo子模块

2.1 引入依赖

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

<dependencyManagement>
    <dependencies>
        <dependency>
            <groupId>org.springframework.cloud</groupId>
            <artifactId>spring-cloud-dependencies</artifactId>
            <version>Hoxton.SR12</version>
            <type>pom</type>
            <scope>import</scope>
        </dependency>
    </dependencies>
</dependencyManagement>

2.2 启动类

/**
 * Copyright (c) 2022 itmentu.com, All rights reserved.
 *
 * @Author: yang
 */
@SpringBootApplication
public class GateWayDemoApplication {
    public static void main(String[] args) {
        SpringApplication.run(GateWayDemoApplication.class, args);
    }
}

2.3 配置

server:
  port: 8502
spring:
  application:
    name: gateway
  cloud:
    consul:
      host: 192.168.184.128
      port: 8500
      discovery:
        service-name: ${spring.application.name}
        register: false

2.4 路由配置

gateway:
  # 路由si(集合)
  routes:
    # id唯一标识
    - id: consumer-service-route
      # 路由服务地址 
      uri: lb://service-consumer
      # 断言
      predicates:
        - Path=/**

代码说明:

1:routes:id表示路由标识,唯一即可,当前案例中表示消费者服务对应的路由
2:uri: lb://service-consumer表示uri使用负载均衡模式,lb表示loadbalance,”lb:“后跟注册中心对应的服务名

2.5 改造原本的service-consumer服务

新增@EnableDiscoveryClient注解注册开启注册中心

/**
 * Copyright (c) 2022 itmentu.com, All rights reserved.
 *
 * @Author: yang
 */
@SpringBootApplication
@EnableFeignClients
@EnableCircuitBreaker
@EnableHystrixDashboard
@EnableDiscoveryClient
public class ServiceConsumerApplication {

    public static void main(String[] args) {
        SpringApplication.run(ServiceConsumerApplication.class, args);
    }

    @Bean
    @LoadBalanced//开启负载均衡
    public RestTemplate restTemplate(){
        return new RestTemplate();
    }
}

修改配置为注册到注册中心

spring:
  cloud:
    consul:
      discovery:
        register: true

2.6 测试

通过http://localhost:8502/consumer/hello-feign地址访问消费者服务接口

image-20220320180509185

3 路由前缀

3.1 添加前缀

gateway中可以通过配置路由的过滤器PrefixPath 实现映射路径中的前缀添加。可以起到隐藏接口地址的作用,避免接口地址暴露。

配置请求地址添加路径前缀过滤器

spring:
    gateway:
      routes:
          filters:
            - PrefixPath=/consumer

测试

重启路由服务访问

http://localhost:8502/hello-feign

结果如下,说明路由到了

http://localhost:8002/consumer/hello-feign

image-20220320181817680

3.2 去除前缀

gateway中通过配置路由过滤器StripPrefix,实现映射路径中地址的去除。通过StripPrefix=1来指定路由要去掉的前缀个数。如:路径/api/consumer/hello-feign将会被路由到/consumer/hello-feign

配置去除路径前缀过滤器

spring:
    gateway:
      routes:
          filters:
            - StripPrefix=1

测试

重启路由服务访问

http://localhost:8502/api/consumer/hello-feign

结果如下,说明被路由到了

/consumer/hello-feign

image-20220320182253539

4 过滤器

过滤器作为网关的其中一个重要功能,就是实现请求的鉴权。前面的路由前缀章节中的功能也是使用过滤器实现的。

4.1 常见过滤器

Gateway自带过滤器有几十个,常见自带过滤器有:

过滤器名称说明
StripPrefix对匹配上的请求路径去除前缀
PrefixPath对匹配上的请求路径添加前缀
AddRequestHeader对匹配上的请求加上Header
AddRequestParameter对匹配上的请求添加参数
AddResponseHeader对从网关返回的响应添加Header

4.2 常见场景

  • 请求鉴权:如果没有访问权限,直接进行拦截
  • 异常处理:记录异常日志
  • 服务调用时长统计

4.3 过滤器配置说明

Gateway有两种过滤器

局部过滤器:只作用在当前配置的路由上,上面我们配置的路由前缀过滤器就是局部过滤器
全局过滤器:作用在所有路由上。

4.4 全局过滤器配置演示

全局配置过滤器AddResponseHeader

spring:
  cloud:
    gateway:
     # 配置全局默认过滤器
      default-filters:
      # 往响应过滤器中加入信息
        - AddResponseHeader=key1,value1

测试

在浏览器中可以看到响应头

image-20220320183325636