Spring Cloud Gateway 网关

Spring Cloud 在最新版本 2020.0.0 开始,已去除了 Zuul 网关的使用,改用 Spring Cloud Gateway 作为网关。

Spring Cloud Gateway 基于 Spring WebFlux 框架实现,相对于 Zuul 来说,性能更高。

本文讲述如何在 Spring Cloud 中使用 Nacos 作为注册中心,通过 Spring Cloud Gateway 实现 API 路由的功能。

启动 Nacos

由于需要使用 Nacos 作为注册中心,网关和微服务都注册到 Nacos,因此,需要先启动一个单机版本的 Nacos。

可以参考 Nacos 官方文档 https://nacos.io/zh-cn/docs/quick-start.html 启动一个单机版本的 Nacos。启动成功后,可以通过地址 http://localhost:8868/nacos 访问,用户名 nacos,密码 nacos

启动 Gateway

在 Spring Cloud 项目 springcloudstudy 基础上创建一个 Spring Boot 子项目(有关如何在 IntelliJ Idea 创建 Spring Boot 子项目,可参考 Spring Cloud 使用 Nacos 作配置中心),添加pom.xml 依赖:

1
2
3
4
5
6
7
8
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
  • spring-cloud-starter-alibaba-nacos-discovery:使用 Nacos 作为注册中心,需要连接上 Nacos
  • spring-cloud-starter-gateway:使用 Spring Cloud Gateway 作为网关

添加 bootstrap.yml 配置:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
 server:
port: 8123

spring:
application:
name: gateway
cloud:
nacos:
discovery:
server-addr: localhost:8868
gateway:
routes:
- id: nacos-provider
uri: lb://nacos-provider
predicates:
- Path=/provider/**
filters:
- StripPrefix=1

网关端口为 8123。由于需要连接 Nacos 注册中心,需要提供服务名称 gateway,以及配置 Nacos 注册中心地址 localhost:8868

接下来是网关的重要配置 spring.cloud.gateway.routes

  • id:自定义路由 id
  • uri:目标服务地址,lb: 表示从微服务注册中心(例如 Nacos)订阅服务,并进行服务的路由,这里配置目标服务为 nacos-provider
  • predicates:路由条件,此处路由条件为当请求路径以 /provider 开头
  • filters:路由过滤器,此处使用过滤器 StripPrefixStripPrefix 为 1 ,即将请求路径前面 1 部分截取掉。例如,请求路径为 http://localhost:8123/provider/echo/leo,转发至后端的请求路径则会变成 /echo/leo

启动主类增加注解 @EnableDiscoveryClient 以连接上注册中心:

1
2
3
4
5
6
7
8
9
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {

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

}

启动微服务

复用文章 《Spring Cloud 使用 Nacos 作注册中心》 服务提供者 nacos-provider 作为路由转发的微服务。

为方便演示,这里我们启动了两个 nacos-provider 微服务的实例,如下图所示:

测试

访问 http://localhost:8123/provider/echo/leo,此时会将请求路由至 nacos-provider 微服务其中一个实例,且请求路径变为 /echo/leo,浏览器输出:

Hello Nacos Discovery leo

附:源代码

完整的源代码请参考:

https://github.com/haozlee/springcloudstudy

参考资料