核心概念
Route(路由):
网关配置的基本组成模块,和Zuul的路由配置模块类似。一个Route模块由一个ID,一个目标URI,一组谓词(断言)和一组过滤器定义。如果断言为真,则路由匹配,目标URI会被访问。
Predicate(谓词):
即java.util.function.Predicate,通过Predicate实现路由匹配条件
Filter(过滤器)
和Zuul的过滤器在概念上类似,可以使用它拦截和修改请求,并且对上游的响应,进行二次处理。过滤器为org.springframework.cloud.gateway.filter.GatewayFilter类的实例。
配置
maven配置
pom.xml
<dependencies>
<dependency>
<groupId>org.springframework.cloud</groupId>
<artifactId>spring-cloud-starter-gateway</artifactId>
</dependency>
</dependencies>
yml配置
application.yml
server:
port: 9201
spring:
cloud:
gateway:
routes:
- id: user-cervice #路由的ID
uri: http://localhost:8201/user/{id} #匹配后路由地址
predicates: # 断言,路径相匹配的进行路由
- Path=/user/{id}
配置中心
server:
port: 8080
spring:
application:
name: gateway
cloud:
gateway:
discovery:
locator:
enabled: true
logging:
level:
org.springframework.cloud.gateway: trace
org.springframework.http.server.reactive: debug
org.springframework.web.reactive: debug
reactor.ipc.netty: debug
eureka:
client:
serviceUrl:
defaultZone: http://localhost:8761/eureka/
spring.cloud.gateway.discovery.locator.enabled:表示是否与服务发现组件(register)进行结合,通过 serviceId(必须设置成大写)转发到具体的服务实例。默认为 false,设为 true 便开启通过服务中心的自动根据 serviceId 创建路由的功能。路由访问方式:http://Gateway_HOST:Gateway_PORT/ 大写的 serviceId/**,其中微服务应用名默认大写访问。
logging.level:日志配置策略。
然后我们启动服务注册中心、服务提供者、服务网关,访问地址:http://localhost:8080/EUREKACLIENT/index,我们可以看到和之前的界面完全一样。
路由谓词工厂
路由谓词工厂 (Route Predicate Factories),路由谓词工厂的作用是:符合Predicate的条件,就使用该路由的配置,否则就不管.
谓词工厂 |
---|
After |
Before |
Between |
Cookie |
Header |
Host |
Method |
Path |
Query |
RemoteAddr |
过滤器Filter
StripPrefix
对指定数量的路径前缀进行去除的过滤器。
spring:
cloud:
gateway:
routes:
- id: strip_prefix_route
uri: http://localhost:8201
predicates:
- Path=/user-service/**
filters:
- StripPrefix=2
以上配置会把以/user-service/开头的请求的路径去除两位,通过curl工具使用以下命令进行测试。
curl http://localhost:9201/user-service/a/user/1
相当于发起该请求:
curl http://localhost:8201/user/1
PrefixPath
与StripPrefix过滤器恰好相反,会对原有路径进行增加操作的过滤器。
以上配置会对所有GET请求添加/user路径前缀,通过curl工具使用以下命令进行测试。
curl http://localhost:9201/1
相当于发起该请求:
curl http://localhost:8201/user/1
[
](http://localhost:8201/user/1)
参考
https://www.cnblogs.com/crazymakercircle/p/11704077.html
https://xinlichao.cn/back-end/java/spring-cloud-gateway/