赞
踩
SpringCloud Gateway是Spring官方最新推出的一款基于SpringFramework5,Project Reactor和SpringBoot 2之上开发的网关。
它与第一代网关Zuul不同的是:gateway是异步非阻塞的(netty + webflux实现);zuul是同步阻塞请求的
Gateway由三大组成部分,分别是路由、断言、过滤器。

谓词Predicate对于熟悉Java8函数式编程的开发者来说并不会陌生,这里不做累述。简单地理解,predicate在gateway中是路径相匹配的进行路由。
静态路由配置写在配置文件中(yml或者properties文件中),端点是:spring.cloud.gateway
静态路由的缺点非常明显,每次改动都要重新部署网关模块。
路由信息在Nacos中维护,可以实现动态变更

第一步:启动nacos,创建配置文件,如下图所示:
具体的配置信息如下:
- [
- {
- "id": "e-commerce-nacos-client-imooc",
- "predicates": [
- {
- "args": {
- "pattern": "/imooc/ecommerce-nacos-client/**"
- },
- "name": "Path"
- }
- ],
- "uri": "lb://e-commerce-nacos-client"
- }
- ]
- 复制代码
第二步:创建Gateway工程
引入的依赖有:
- <dependency>
- <groupId>com.alibaba.cloud</groupId>
- <artifactId>spring-cloud-starter-alibaba-nacos-discovery</artifactId>
- <version>2.2.3.RELEASE</version>
- </dependency>
- <dependency>
- <groupId>org.springframework.cloud</groupId>
- <artifactId>spring-cloud-starter-gateway</artifactId>
- </dependency>
- 复制代码
bootstrap.yml的配置如下:
- server:
- port: 9001
- servlet:
- context-path: /imooc
-
- spring:
- application:
- name: e-commerce-gateway
- cloud:
- nacos:
- discovery:
- enabled: true # 如果不想使用 Nacos 进行服务注册和发现, 设置为 false 即可
- server-addr: 127.0.0.1:8848 # Nacos 服务器地址
- namespace: fa2e39fc-7e9b-4b8c-bd35-53543d2e1d8a
- metadata:
- management:
- context-path: ${server.servlet.context-path}/actuator
- # 静态路由

Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。