API网关,就是指系统的统一入口,它封装来应用程序的内部结构,为客户端提供统一服务,一些与业务本身功能无关的公共逻辑可以在这里实现,诸如认证,鉴权,监控,路由转发等等。
SpringCloud Gateway 是 Spring Cloud 的一个全新项目,该项目是基于 Spring 5.0,Spring Boot 2.0 和 Project Reactor 等技术开发的网关,它旨在为微服务架构提供一种简单有效的统一的 API 路由管理方式。
SpringCloud Gateway 作为 Spring Cloud 生态系统中的网关,目标是替代Netflix Zuul,其不仅提供统一的路由方式,而且基于Fliter链的方式提供了网关基本的功能,例如:安全,监控/指标和限流。
(1)优点:
性能强劲:是第一代网关Zuul的1.6倍
功能强大:内置了很多使用的功能,例如转发,监控,限流等
设计优雅,容易扩展
(2)缺点:
其实现依赖Netty与WebFlux,不是传统的Servlet编程模型,学习成本高
不能将其部署在tomcat,jetty等Servlet容器里,只能打成jar包执行
需要Spingboot2.0及以上的版本,才支持。
org.springframework.cloud
spring-cloud-starter-gateway
@SpringBootApplication
public class RuoYiGatewayApplication
{
public static void main(String[] args)
{
SpringApplication.run(RuoYiGatewayApplication.class, args);
}
}
server:
port: 8080
spring:
application:
name: ruoyi-gateway
cloud:
gateway:
routes: #路由数组[路由就是指定当请求满足什么条件的时候转到哪个微服务]
# 系统模块
- id: ruoyi-system #当前路有的标示,要求唯一
uri: http://localhost:9201/ #请求要转发到的地址
predicates: #断言(就是路由转发要满足的条件)
- Path=/system/** #当前请求路径满足Path指定的规则时,才进行路有转发
filters: #过滤器,请求在传递过程中可以通过过滤器对其进行一定的修改
- StripPrefix=1 #转发之前去掉1层路径
在地址栏输入 localhost:8080/system/user/1就会自动跳转到 localhost:9201/user/1
其中路径中的system被过滤掉,8080变成9201
(1)现在在配置文件中写死了转发路径的地址,我们需要使用nacos获取此地址,
(2)并使用 uri: lb://ruoyi-system #请求要转发到的地址 自动实现负载均衡
第1步,加入nacos依赖
com.alibaba.cloud
spring-cloud-starter-alibaba-nacos-discovery
第2部:应用加上注解@EnableDiscoveryClient
@SpringBootApplication
@EnableDiscoveryClient
public class RuoYiGatewayApplication
{
public static void main(String[] args)
{
SpringApplication.run(RuoYiGatewayApplication.class, args);
}
}
第3部:修改配置文件
server:
port: 8080
spring:
application:
name: ruoyi-gateway
cloud:
nacos:
discovery:
server-addr: 127.0.0.1:8848
gateway:
discovery:
locator:
lowerCaseServiceId: true
enabled: true #让gateway可以发现nacos的微服务
routes: #路由数组[路由就是指定当请求满足什么条件的时候转到哪个微服务]
# 系统模块
- id: ruoyi-system #当前路有的标示,要求唯一
uri: lb://ruoyi-system #请求要转发到的地址
predicates: #断言(就是路由转发要满足的条件)
- Path=/system/** #当前请求路径满足Path指定的规则时,才进行路有转发
filters: #过滤器,请求在传递过程中可以通过过滤器对其进行一定的修改
- StripPrefix=1 #转发之前去掉1层路径