一、 Gateway 简介
Spring Cloud Gateway 是Spring Cloud团队的一个全新项目,基于Spring 5.0、SpringBoot2.0、Project Reactor 等技术开发的网关。 旨在为微服务架构提供一种简单有效统一的API路由管理方式。
Spring Cloud Gateway 作为SpringCloud生态系统中的网关,目标是替代Netflix Zuul。Gateway不仅提供统一路由方式,并且基于Filter链的方式提供网关的基本功能。例如:安全,监控/指标,和限流。
本身也是一个微服务,需要注册到Eureka
网关的核心功能:过滤、路由
核心概念:通过画图解释
- 路由(route):
- 断言Predicate函数:路由转发规则
- 过滤器(Filter):
实现步骤:
- 创建gateway_service工程SpringBoot
- 编写基础配置
- 编写路由规则,配置静态路由策略
- 启动网关服务进行测试
1. 创建gateway_service工程SpringBoot
2. 编写基础配置
2.1GatewayServerApplication
package com.william;import org.springframework.boot.SpringApplication;
import org.springframework.boot.autoconfigure.SpringBootApplication;
import org.springframework.cloud.client.discovery.EnableDiscoveryClient;@SpringBootApplication
@EnableDiscoveryClient //开启服务发现
public class GatewayServerApplication {public static void main(String[] args) {SpringApplication.run(GatewayServerApplication.class, args);}}
3. 编写路由规则,配置静态路由策略
3.1 application.yml
server:port: 10010
spring:application:name: api-gateway # 应用名cloud:gateway:# 路由si(集合)routes:# id唯一标识,(可自定义)- id: user-service-route# 路由服务地址uri: http://127.0.0.1:9091# 路由拦截地址(断言)predicates:- Path=/user/**
# Eureka服务中心配置
eureka:client:service-url:# 注册Eureka Server集群defaultZone: http://127.0.0.1:10086/eureka
4. 启动网关服务进行测试
二、动态路由
刚才路由规则中,我们把路径对应服务地址写死了!如果服务提供者集群的话,这样做不合理。应该是根据服务名称,去Eureka注册中心查找服务对应的所有实例列表,然后进行动态路由!
1.修改映射配置:通过服务名称获取
因为已经配置了Eureka客户端,可以从Eureka获取服务的地址信息,修改application.yml文件如下
# 首先,路由规则变成动态了,# lb协议,是网关的特有协议,自动支持负载均衡uri: lb://user-service
2.测试结果
根据随机策略进行