简介
网关作为流量的入口,常用功能包括路由转发、权限校验、限流控制等;而SpringCloud Gateway 作为SpringCloud 官方推出的第二代网关框架,取代了Zuul网关
特征
- 建立在Spring Framework 5,Project Reactor和Spring Boot 2.0之上
- 能够匹配任何请求属性上的路由
- 路由有独特的断言和过滤器
- 集成断路器
- 集成Spring Cloud DiscoveryClient integration
- 易于编写断言和过滤器
- 请求限速
- 路径重写
在使用前需要了解几个基本的概念
Route: 路由,网关的基本构建块。它由ID,目标URI,断言集合和过滤器集合定义。如果断言为true,则匹配路由
Predicate: 断言,Java8 断言函数,允许开发人员匹配当次请求的任何信息;它的作用,当满足断言规则则路由到指定路径
Filter: 过滤器,在发送请求之前或之后修改请求和响应
工作流程
简单的说,当我们的请求到达网关,网关先利用断言,来判断这次请求是否符合路由规则,如果符合则按照路由规则经过一系列的过滤路由到指定地方
使用Gateway
网关,作为客户请求的第一层,直接通过网关转发客户请求到对应的路径,所以应该是一个单独的模块,并且为了方便建议使用80端口
1. 导入jar包
<!-- gateway -->
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<!-- Nacos 服务注册发现 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
</dependency>
<!-- nacos 配置中心 -->
<dependency>
<groupId>com.alibaba.cloud</groupId>
<artifactId>spring-cloud-starter-alibaba-nacos-config</artifactId>
</dependency>
2. 编写yaml配置
spring:
cloud:
nacos:
discovery:
server-addr: 192.168.0.109:8848
gateway:
routes: # 路由规则,可以配置多种,以数组的方式配置
- id: test_route # 路由ID
uri: https://www.baidu.com # 跳转的路径
predicates: # 断言规则,数组形式配置多个
- Query=url,baidu # 精确匹配,如果携带的参数url等于 "baidu",则跳转
- id: qq_route
uri: https://www.qq.com
predicates:
- Query=url,qq
application:
name: gulimall-gateway
server:
port: 80
3. 启动测试
@SpringBootApplication
@EnableDiscoveryClient //服务注册发现
public class GulimallGatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GulimallGatewayApplication.class, args);
}
}
在配置中,我做了两个路由转发,当请求携带 “baidu” 参数跳转到百度网页,携带 “qq” 跳转到qq主页