- 前言
- 环境
- 为什么要使用网关
- Gateway的优点
- Gateway 核心概念
- Gateway 整合实例
- 网关 core-gateway
- 用户中心 user-center
- 测试
Spring Cloud Gateway是SpringCloud生态的第二代网关(第一代是Zuul),基于Netty、Reactor以及WebFlux构建
环境
Spring Cloud Hoxton.SR9 + Spring Cloud Alibaba 2.2.6.RELEASE
为什么要使用网关
- 简化登录认证,网关统一认证再转发到其它微服务
- 网关方式对外暴露的永远是一个域名,客户端配置简单
Gateway的优点
- 性能强劲,是第一代网关Zuul 1.x的1.6倍
- 内置了很多实用功能,如转发、监控、限流等
- 易扩展
Gateway 核心概念
| 名称 | 解释 | 作用 |
|---|---|---|
| Route | 路由 | 一个转发规则,包含ID、目标URL、Predicate集合一级Filter集合 |
| Predicate | 谓词,也称断言 | 控制请求是否走转发规则的条件 |
| Filter | 过滤器 | 修改请求以及响应,可以为路由添加业务逻辑 |
Gateway 整合实例 网关 core-gateway
- pom.xml
4.0.0 org.springframework.boot spring-boot-starter-parent2.3.2.RELEASE com.coisini core-gateway0.0.1-SNAPSHOT core-gateway Gateway project for Spring Boot 1.8 Hoxton.SR9 2.2.6.RELEASE org.springframework.cloud spring-cloud-starter-gatewaycom.alibaba.cloud spring-cloud-starter-alibaba-nacos-discoveryorg.springframework.boot spring-boot-starter-actuatororg.springframework.boot spring-boot-starter-testtest org.springframework.cloud spring-cloud-dependencies${spring-cloud.version} pom import com.alibaba.cloud spring-cloud-alibaba-dependencies${spring-cloud-alibaba.version} pom import org.springframework.boot spring-boot-maven-plugin
- application.yml
spring:
application:
name: core-gateway
cloud:
nacos:
discovery:
server-addr: localhost:8848
gateway:
discovery:
locator:
# 让gateway通过服务发现组件找到其它的服务
enabled: true
server:
port: 8040
# Actuator
management:
endpoints:
web:
exposure:
include: "*"
endpoint:
health:
show-details: always
用户中心 user-center
- TestController.java
@RestController
@Slf4j
public class TestController {
@GetMapping("/test/{name}")
public String test(@PathVariable String name) {
log.info("请求...");
return "hello " + name;
}
}
测试
- 启动网关,访问Nacos控制台
- 测试接口访问
Gateway的转发规律:访问${GATEWAY_URL}/{微服务X}/xx 会转发到微服务X 的 /xx 路径



