??Spring Cloud Gateway 是 Spring Cloud 体系的第二代网关组件,基于 Spring 5.0 的新特性 WebFlux 进行开发,底层网络通信框架使用的是 Netty,所以其吞吐量高、性能强劲,取代了第一代的网关组件 Zuul。Spring Cloud Gateway 组件的核心是一系列的过滤器,通过这些过滤器可以将客户端发送的请求转发到对应的微服务。Spring Cloud Gateway 是加在整个微服务最前沿的防火墙和代理器,隐藏微服务结点 IP 端口信息,从而加强安全保护。Spring Cloud Gateway 本身也是一个微服务,需要注册到服务注册中心。
?? 路由(route)
路由是网关的基本模块,由一个ID、一个目的URL、一组断言工厂、一组 Filter 组成。如果路由断言为真,说明请求 URL 和配置路由匹配。
?? 断言(Predicate)
Spring Cloud Gateway 中的断言函数输入类型是 Spring5.0 框架中的 ServerWebExchange。Spring Cloud Gateway 的断言函数允许开发者去定义匹配来自于 Http Request 中的任何信息比如请求头和参数。
?? 过滤器(Filter)
一个标准的 Spring WebFilter。Spring Cloud Gateway 中的 Filter 分为两种类型的 Filter,分别是 Gateway Filter 和 Global Filter。过滤器 Filter 将会对请求和响应进行修改处理。
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
server:
port: 8100
spring:
application:
name: gateway-server # 应用名称,在 Eureka 中作为 id 标识
cloud:
gateway:
routes:
# 路由 id 随便写
- id: info-server
# 服务地址,若使用了注册中心可以使用服务名 lb://info-server
uri: http://127.0.0.1:8200
# 服务路径
predicates:
- Path=/info/**
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:8000/eureka
server:
enable-self-preservation: false # 关闭自我保护模式, 默认为打开
eviction-interval-timer-in-ms: 5000 # 续期时间,即扫描失效服务的间隔时间
/**
* Created with IntelliJ IDEA.
*
* @author Demo_Null
* @date 2020/11/10
* @description
*/
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
??启动服务后,我们发现不论是直接使用 http://127.0.0.1:8200/info/get
请求服务,还是通过网关 http://127.0.0.1:8100/info/get
请求服务都没有问题。
未完待续