8、网关 Spring Cloud Gateway

 网关作用:为微服务提供统一的路由管理,可以在路由管理基础上进行一系列的过滤,可以做一系列的监控操作,限流。

1 Gateway 简介

Spring Cloud Gateway 是Spring Cloud团队的一个全新项目,基于Spring 5.0、SpringBoot2.0、Project Reactor 等技术开发的网关。 旨在为微服务架构提供一种简单有效统一的API路由管理方式。

Spring Cloud Gateway 作为SpringCloud生态系统中的网关,目标是替代Netflix Zuul。Gateway不仅提供统一路由方式,并且基于Filter链的方式提供网关的基本功能。例如:安全,监控/指标,和限流。

本身也是一个微服务,需要注册到Eureka

网关的核心功能:路由,过滤

核心概念:通过画图解释,如下图所示↓

  • 路由(route):

  • 断言Predicate函数:路由转发规则

  • 过滤器(Filter):

  •  

 快速入门

实现步骤:

 1. 创建gateway-service工程SpringBoot
 2. 编写基础配置
 3. 编写路由规则,配置静态路由策略
 4. 启动网关服务进行测试

实现过程:

(1)创建一个子工程gateway-service

(2)pom.xml依赖

     <dependencies>
         <!--网关依赖-->
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-gateway</artifactId>
         </dependency>
         <!-- Eureka客户端 -->
         <dependency>
             <groupId>org.springframework.cloud</groupId>
             <artifactId>spring-cloud-starter-netflix-eureka-client</artifactId>
         </dependency>
     </dependencies>

(3)启动类

创建启动类com.sen.GatewayApplication,代码如下:

 @SpringBootApplication
 @EnableDiscoveryClient// 开启Eureka客户端发现功能
 public class GatewayApplication {
     public static void main(String[] args) {
         SpringApplication.run(GatewayApplication.class,args);
     }
 }

(4)application.yml配置

 # 注释版本
 server:
   port: 18084
 spring:
   application:
     name: api-gateway # 应用名
 # Eureka服务中心配置
 eureka:
   client:
     service-url:
       # 注册Eureka Server集群
       defaultZone: http://127.0.0.1:7001/eureka

 路由配置

 

通过网关配置一个路由功能,用户访问网关的时候,如果用户请求的路径是以/user开始,则路由到user-provider服务去,修改application.yml配置即可实现,配置如下:

 server:
   port: 18084
 spring:
   application:
     # 应用名
  
  • 0
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值