springcloud微服务(二十三)-网关GateWay基础知识
一、GateWay是什么
GateWay是spring Cloud中很重要的组件-网关,在1.x版本中都是采用Zuul网关。
GateWay旨在提供一种简单并有效地方式来对API进行路由,以及提供一些强大的过滤功能,例如:熔断、限流、重试等。而为了提升网关的性能,SpringCloud Gateway是基于WebFlux框架实现的,而WebFlux框架底层则使用了高性能的Reactor模式通信框架Netty.
二、作用
反向代理
鉴权
流量控制
熔断
日志监控
。。。。
三、微服务架构中网关在哪里
四、工作流程
客户端向spring Cloud Gateway 发出请求。然后在Gateway Handler Mapping中找到与请求相匹配的路由,将其发送到Gateway Web Handler。
Handler再通过指定的过滤器链来将请求发送到我们实际的服务执行业务逻辑,然后返回。过滤器之间用虚线分开是因为过滤器可能会发送代理请求之前("pre")或之后("post")执行业务逻辑。
Filter在“pre”类型的过滤器可以做参数检验、权限检验、流量控制、日志输出、协议转换等,
在“post”类型的过滤器中可以做响应内容、响应头的修改,日志的输出,流量监控等有这非常重要的作用。
五、代码实现
5.1 新建module
cloud-gateway-gateway9527
5.2 修改pom文件
<dependencies> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-gateway</artifactId> </dependency> <dependency> <groupId>otc.orientsec</groupId> <artifactId>cloud-api-commons</artifactId> <version>1.0-SNAPSHOT</version> </dependency> <dependency> <groupId>org.projectlombok</groupId> <artifactId>lombok</artifactId> <optional>true</optional> </dependency> <dependency> <groupId>org.springframework.cloud</groupId> <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId> </dependency> </dependencies>
5.3 修改application.yml文件
server: port: 9527 spring: application: name: cloud-gateway-server cloud: gateway: routes: - id: payment_routh #路由的ID,没有固定规则但要求保持唯一 uri: http://127.0.0.1:8001 #匹配后提供的路由地址 predicates: - Path=/payment/get/** #断言,路径相匹配的进行路由 - id: payment_routh2 uri: http://127.0.0.1:8001 #匹配后提供的路由地址 predicates: - Path=/payment/lb/** eureka: client: fetch-registry: true register-with-eureka: true service-url: defaultZone: http://eureka7001.com:7001/eureka/
5.4 新建主启动类
@SpringBootApplication @EnableDiscoveryClient public class GateWayMain9527 { public static void main(String[] args) { SpringApplication.run(GateWayMain9527.class,args); } }
六、测试
启动Eureka7001,启动payment8001,启动GateWay9527
请求:
两个请求都成功。
下一篇:
微服务架构的好处和弊端