- Gateway 概念(这里指网关)
zuul1 官网:https://github.com/Netflix/zuul/wiki
Gateway官网:https://spring.io/projects/spring-cloud-gateway#overview
SpringCloud Gateway 使用的是Webflux中的reactor-netty响应式编程组件,底层使用Netty通讯框架。
作用:
* 反向代理
* 鉴权
* 流量控制
* 熔断
* 日志监控
-
三大核心概念
- 路由 路由是构建网关的基本模块,它由ID 目标Url ,一系列的断言和过滤器组成,如果断言为true则匹配路由
- 断言 开发人员可以匹配HTTP请求中所有的内容(请求头,请求参数),如果请求与断言匹配则进行路由
- 过滤器 指的是Spring框架中Gateway Filter的实例,使用实例,可以在请求被路由前或者之后对请求进行修改。
-
Gateway工作流程
-
入门配置
-
通过微服务名实现动态路由
-
Predicate(断言) 的使用
-
Filter(过滤器)的使用
-
工程案例
-
新建module cloud-gateway9527
-
修改POM
<!--gateway --> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency>
-
修改YML
server: port: 9527 eureka: instance: hostname: cloud-gateway-service client: # 向服务注册中心注册自己 register-with-eureka: true # 是否从EurekaServer 抓取已有的注册信息,默认为true。单节点无所谓,集群必须设置为true才能配合ribbon使用负载均衡 fetch-registry: true service-url: #defaultZone: http://eureka7001.com:7001/eureka # 单机版 defaultZone: http://eureka7001.com:7001/eureka,http://eureka7002.com:7002/eureka # 集群版 spring: application: name: cloud-gateway
-
写主启动
/** * @auther cyq * @create 21:18 2020/6/15 */ @SpringBootApplication @EnableEurekaClient public class GatewayMain9527 { public static void main(String[] args) { SpringApplication.run(GatewayMain9527.class,args); } }
-
写网关配置 注解版
spring: application: name: cloud-gateway cloud: gateway: routes: - id: order_routh # order_routh 路由id,没有固定规则但要求唯一,建议配合服务名 uri: http://localhost:80 predicates: - Path=/consumer/payment/hystrix/ok/** # 断言,路径相匹配进行路由 - id: order_routh2 # order_routh 路由id,没有固定规则但要求唯一,金阿姨配合服务名 uri: http://localhost:80 predicates: - Path=/consumer/payment/circuit/** # 断言,路径相匹配进行路由
通过注解进行路由,在这里我进行的是路径匹配,还有其他匹配规则
我用9527作为网关端口挡在真正的服务实例之前,通过匹配规则就路由
真实请求消费地址:注意,我请求地址的端口
真实请求提供地址:注意,我请求地址的端口
网关地址:注意,我请求地址的端口
-
在代码中注入RouteLocator的Bean
写一个配置类
/** * @auther cyq * @create 0:00 2020/6/16 */ @Configuration public class GatewayConfig { /** * @description: <路由转发> * * @auther: cyq * @create: 0:09 2020/6/16 */ @Bean public RouteLocator routes(RouteLocatorBuilder builder){ RouteLocatorBuilder.Builder routes = builder.routes(); routes.route("path_route_baidu1", r ->r.path("/mil").uri("http://news.baidu.com/mil")).build(); return routes.build(); } }
实现一个百度信息路由转发
-
r.path("/mil").uri(“http://news.baidu.com/mil”)).build();
return routes.build();
}
}
```
实现一个百度信息路由转发