Spring Cloud Gateway网关
一些概念
路由(route) 路由信息的组成:由一个ID、一个目的URL、一组断言工厂、一组Filter组成。如果路由断言 为 真,说明请求URL和配置路由匹配。
断言(Predicate) Spring Cloud Gateway中的断言函数输入类型是Spring 5.0框架中的 ServerWebExchange。Spring Cloud Gateway的断言函数允许开发者去定义匹配来自于HTTP Request中的 任何信息比如请求头和参数。
过滤器(Filter) 一个标准的Spring WebFilter。 Spring Cloud Gateway中的Filter分为两种类型的Filter,分 别是Gateway Filter和Global Filter。过滤器Filter将会对请求和响应进行修改处理
依赖
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
</dependency>
</dependencies>
启动类
@SpringBootApplication
@EnableDiscoveryClient
public class GatewayApplication {
public static void main(String[] args) {
SpringApplication.run(GatewayApplication.class, args);
}
}
客户端的请求地址与微服务的服务地址如果不一致的时候,可以通过配置路径过滤器实现路径前缀的添加和去除。
在gateway中可以通过配置路由的过滤器PrefixPath,实现映射路径中地址的添加;
在gateway中可以通过配置路由的过滤器StripPrefix,实现映射路径中地址的去除;
application.yml文件实例
#示范案例
server:
port: 8086
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: bill-service-route
# 代理的服务地址
uri: http://127.0.0.1:8080
# 路由断言,可以配置映射路径
predicates:
- Path=/api/consumer/**
filters:
# 表示过滤1个路径,2表示两个路径,以此类推
- StripPrefix=1
- id: bill-service-route2
# 代理的服务地址
#uri: http://127.0.0.1:9094
uri: http://127.0.0.1:9094
# 路由断言,可以配置映射路径
predicates:
- Path=/api/bill/**
filters:
# 表示过滤1个路径,2表示两个路径,以此类推
- StripPrefix=1
globalcors:
corsConfigurations:
'[/**]':
#allowedOrigins: * # 这种写法或者下面的都可以,*表示全部
allowedOrigins:
- "http://docs.spring.io"
allowedMethods:
- GET
- POST
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
实际效果:
localhost:8086/api/consumer/add?id=10 => localhost:8080/consumer/add?id=6
面向服务的路由
如果同一服务有多个实例的话,这样做显然不合理。 应该根 据服务的名称,去Eureka注册中心查找 服务对应的所有实例列表,然后进行动态路由!
server:
port: 8086
spring:
application:
name: api-gateway
cloud:
gateway:
routes:
# 路由id,可以随意写
- id: bill-service-route
# 代理的服务地址
uri: lb://user-service
# 路由断言,可以配置映射路径
predicates:
- Path=/api/consumer/**
filters:
# 表示过滤1个路径,2表示两个路径,以此类推
- StripPrefix=1
- id: bill-service-route2
# 代理的服务地址
#uri: http://127.0.0.1:9094
uri: lb://user-service
# 路由断言,可以配置映射路径
predicates:
- Path=/api/bill/**
filters:
# 表示过滤1个路径,2表示两个路径,以此类推
- StripPrefix=1
globalcors:
corsConfigurations:
'[/**]':
#allowedOrigins: * # 这种写法或者下面的都可以,*表示全部
allowedOrigins:
- "http://docs.spring.io"
allowedMethods:
- GET
- POST
eureka:
client:
service-url:
defaultZone: http://127.0.0.1:10086/eureka
instance:
prefer-ip-address: true
全局过滤器:不需要在配置文件中配置,作用在所有的路由上;实现 GlobalFilter 接口即可。