Spring Cloud Gateway入门

Posted by Kaka Blog on December 1, 2020

前言

Spring Cloud Gateway 是 Spring Cloud 的一个全新项目,该项目是基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。

其不仅提供统一的路由方式,并且基于 Filter 链的方式提供了网关基本的功能,例如:安全,监控/指标,和限流。

快速上手

  • Spring Cloud版本:Greenwich.SR6
  • Spring Boot版本:2.1.7.RELEASE

添加项目需要使用的依赖包:

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

添加配置文件配置信息:

spring.application.name=gateway
server.port=9292
spring.cloud.nacos.discovery.server-addr=127.0.0.1:8848
#哨兵
#spring.cloud.sentinel.transport.dashboard=localhost:8080
#打开sentinel
feign.sentinel.enabled=true
spring.cloud.gateway.routes[0].id=producer01
spring.cloud.gateway.routes[0].uri=lb://producer01
spring.cloud.gateway.routes[0].predicates[0]=Path=/produce/**
spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1

各字段含义如下:

  • id:我们自定义的路由 ID,保持唯一
  • uri:目标服务地址
  • predicates:路由条件,Predicate 接受一个输入参数,返回一个布尔值结果。该接口包含多种默认方法来将 Predicate 组合成其他复杂的逻辑(比如:与,或,非)。
  • filters:过滤规则

测试

启动nacos,启动produce01服务,启动gateway服务,浏览器访问地址:http://localhost:9292/produce/order/fang/123/100/create

Q&A

1、启动时报错:Please remove spring-boot-starter-web dependency

解决:

在本项目中,父模块引入了spring-boot-starter-web依赖,去掉该依赖即可。

2、访问访问404,路由不到服务。

解决:

查看是否缺少spring.cloud.gateway.routes[0].filters[0]=StripPrefix=1配置,不能不设置。很奇怪,访问路径前缀有多少个,就要设置多少个StripPrefix, 例如如果predicates[0]=Path=/produce/test/**,则StripPrefix=2才有效果。

参考资料