1.网关很重要的一大内容是路由匹配(有些类似springMVC的contoller,不过这个匹配可以按照时间匹配,可以选用after 、between、before)
2.路由匹配
https://www.geekdigging.com/2019/08/31/2648795174/
(1)after before between 混合使用
使用cookie匹配
- Cookie=sessionid,name
- After=2020-06-20T06:06:06+08:00[Asia/Shanghai]
- Between=2020-06-20T06:06:06+08:00[Asia/Shanghai],2022-06-20T06:06:06+08:00[Asia/Shanghai]
- Before=2022-06-20T06:06:06+08:00[Asia/Shanghai]
//测试
curl http://localhost:8080 --cookie “sessionid=name”
(2) header匹配
- Header=baidu, \d+
//测试(命令提示符)
curl http://localhost:8080 -H
(3)Host匹配
- Host=**.baidu
//测试
curl http://localhost:8080 -H "Host:aaa.baidu"
(4)提交方式(get,post匹配) 参数匹配
- Method=GET
//匹配http://localhost:8080?name=stu_name1,http://localhost:8080?name=stu_name2
(5)参数匹配(包括长度限制)
#stu_name.后面一个点代表一个字符
- Query=name, stu_name..
//测试
curl -X GET http://localhost:8080?name=stu_name01
3.只能访问网关端口
(1)(使用网关能正常获取到数据,直接使用服务端口不能获取到数据)
比如访问服务端口http://localhost:8081/foo 获取到的foo值为null
访问网关端口 http://localhost:8080/foo 正常获取到数据
网关项目关键实现
server:
port: 8080
spring:
application:
name: api-gateway
cloud:
gateway:
discovery:
locator:
enabled: true
routes:
- id: add_request_parameter_route
#格式为:lb://应用注册服务名
uri: lb://spring-cloud-producer
filters:
- AddRequestParameter=foo, bar
predicates:
- Method=GET
eureka:
client:
service-url:
defaultZone: http://localhost:8761/eureka/
logging:
level:
org.springframework.cloud.gateway: debug
使用lb://spring-cloud-producer则在前端访问时就可不必要像下面这样暴露出微服务名
http://localhost:8081/spring-cloud-producer/hello?name=spring&token=aa
(2) 在网关处给请求参数foo赋值
- AddRequestParameter=foo, bar